0

sorry to say, I'm not very experienced with Java. I'm using eclipse as IDE. Eclispe complains about unchecked cast which I can not understand. Please refer to the code snipet. How to make this right in general ?

public Liberty2Server(ArrayList<Map<String,String>> libertySourceFiles , String basePath) throws FileNotFoundException , IllegalArgumentException {
    // check input file path
    for( Object map : libertySourceFiles) {
        Map<String,String> mp = (Map<String,String>) map ;  // <==Eclipse complains here: Unchecked cast from Object to Map<String,String>

Any hint is welcome

Rolf

1
  • 2
    A hint perhaps unrelated to your immediate issue. As soon as I start passing around complex collection compositions (e.g. a list of maps) I create a specific object representing and containing that. It makes the code less verbose and you can implement the population/iteration and pre/post-conditions in one place Commented Feb 5, 2013 at 10:24

4 Answers 4

3

You can change your for loop and use the explicit type in the collection:

for(Map<String,String> map : libertySourceFiles) {
    Map<String,String> mp = map; //probably not needed any more
}
Sign up to request clarification or add additional context in comments.

Comments

2

It means you are performing a cast which the compiler cannot check is safe.

It warns you that you have to check it's safe.

A better solution is to remove the need for the cast by using

for(Map<String, String> mp : libertySourceFiles) {

Comments

0

Eclipse complains, because you want to cast an Object to a Map<String, String>. Change the type of your running variable map to Map<String, String>, and everything will be fine. You won't even need the variable mpthen.

Comments

0

The problem here is that you upcast the ArrayList<Map<String,String>> element do Object and then downcast it to a generic type. The solution is easy:

public Liberty2Server(ArrayList<Map<String,String>> libertySourceFiles , String basePath) throws FileNotFoundException , IllegalArgumentException {
    // check input file path
    for(  Map<String,String> mp : libertySourceFiles) {
      //  Map<String,String> mp = (Map<String,String>) map ; Not needed anymore
      ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.