• Post Reply Bookmark Topic Watch Topic
  • New Topic

TreeMap  RSS feed

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code gives ArrayIndexBoundExcpetion ,but if in for loop ,i write d.length it works correctly.
I have no of 5,4 elements in key,value pair.
I really couldnt get why it is so .Should work same in both way.


import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo1 {
Map calendar=new TreeMap();
TreeMapDemo1(String d[],String e[])
{
for(int i=0;i<e.length;i++) //with d.length ,works
{
calendar.put(d[i],e[i]);
}
}
public static void main(String args[])
{
String dates[]={"22/10/1974","19/02/2005","22/1122005","29/11/2006"};
String events[]={"Birthday","Anniversary","Marriage","Thankgiving","Independ"};
TreeMapDemo1 tmd=new TreeMapDemo1(dates,events);
System.out.println(tmd.calendar);
}





}
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry ,i forgot to mention 1 thing .

key=value
if number of keys is more than values ,it gives exception.
But iread , TreeMap is supposed to accept nulls. keys/values can be Nulls & Keys =unique.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you index off the end of an array, you don't get null, you get an ArrayIndexOutOfBoundsException. If you use e.length as the loop limit, then the loop tries to read dates[4], which does not exist.

Now, if the definition of dates were

String dates[]={"22/10/1974","19/02/2005","22/1122005","29/11/2006", null};

then things would work fine.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!