Reputation: 125
I'm getting an error on this line
tm.put(temp[j],tm.get(temp[j]).add(i));
when i was compiling my program in eclipse:
The method put(String, ArrayList<Integer>) in the type TreeMap<String,ArrayList<Integer>> is not applicable for the arguments (String, boolean)
The followings are my codes:
TreeMap<String, ArrayList<Integer>> tm=new TreeMap<String, ArrayList<Integer>>();
String[] temp=folders.split(" |,");
for (int j=1;j<temp.length;j++){
if (!tm.containsKey(temp[j])){
tm.put(temp[j], new ArrayList<Integer>(j));
} else {
tm.put(temp[j],tm.get(temp[j]).add(j));
}
}
the folders is something like this
folders="0 Jim,Cook,Edward";
I'm wondering why there's no error on the former put method, but only on the second one.
Upvotes: 0
Views: 7915
Reputation: 83303
ArrayList.add(E)
returns a boolean
value, and thus, you can't incorporate the call within a single statement.
You need to pass an ArrayList<Integer>
object as the second argument to the put
method.
Upvotes: 0
Reputation: 8587
ArrayList.add(E)
returns a boolean
, you simply cannot chain them up.
tm.get(temp[j]).add(j);
is enough, you don't need to put
again.
new ArrayList<Integer>(j)
won't give you an arraylist of one element, the argument is the initialCapacity.
Then, you should declare tm
as Map<String, List<Integer>>
.
Map<String, List<Integer>> tm=new TreeMap<String, List<Integer>>();
String[] temp=folders.split(" |,");
for (int j=1;j<temp.length;j++){
if (!tm.containsKey(temp[j])){
tm.put(temp[j], new ArrayList<Integer>());
}
tm.get(temp[j]).add(j); // This will change the arraylist in the map.
}
Upvotes: 3
Reputation: 4827
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(E)
public boolean add(E e) Appends the specified element to the end of this list and returns a boolean. Hence, the error.
Upvotes: 0
Reputation: 11467
ArrayList::add
returns true in this scenario; that is, it doesn't return the new ArrayList. Try cloning the list, adding to it, and then passing it as an argument.
Upvotes: 0