• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array expert's help needed

 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As it is pretty obvious I get an Array Index out of bound exception.
Is there any way around this, I am trying to get the path of all the files in the root directory into an array of strings.
String[] filesFromDest = new String[500]; this declaration is lame too, is there any way I can keep the string length variable.
Any suggestions will be appreciated and Thanks in Advance.

Console Says:

C:\filesys\fileSys1\Copy (2)
C:\filesys\fileSys1\Copy (2)\Copy (2) (3)
C:\filesys\fileSys1\Copy (2)\Copy (2) (3)\doc - Copy (2) (3) 1 - Copy.txt
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 500
at com.rxBatch.Test.fetchFilesFromDirectory(Test.java:31)
at com.rxBatch.Test.fetchFilesFromDirectory(Test.java:27)
at com.rxBatch.Test.fetchFilesFromDirectory(Test.java:27)
at com.rxBatch.Test.main(Test.java:13)
 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in case you dont want to read the entire code, all I am doing is making a recursive call to a method that checks if we are working on a file or directory. If it is a directory it calls the the method again and if it is a file it stores its path name at the end of a string which we will print at the end.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest answer is to stop using an array and use a List instead (e.g. ArrayList). Then you can add new values as often as you like, and it will grow as necessary.
 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ARRAY LIST
what was i thinking.. 0.o
 
Harsha Smith
Ranch Hand
Posts: 287
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Always prefer Arraylists to Arrays.

Reason....... Arrays are covariant and lists are invariant

example:

class Fruit{}

class Apple extends Fruit{}

class Orange extends Fruit{}


Fruit [] fruits = new Apple[1];

fruits [0] = new Orange(); //compiles perfectly but throws ArrayStoreException when executed



ArrayList<Fruit> fruitList = new ArrayList<Apple>(); //won't compile(type mismatch)


ArrayList<? extends Fruit> fruitList = new ArrayList<Apple>(); compiles but useless as we can't add anything to this list except null


examples taken from the book....Thinking in Java (4th edition)





 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic