• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

TreeMap

 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I didn't do it. You can't prove it. Nobody saw me. The sheep are lying! This tiny ad is my witness!
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic