Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

naming a class instance  RSS feed

 
andy hough
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

I have created a class DList.
Now, to create a new instance of this class the code is:

DList myFirstDList = new DList();

ok so far, I understand this, however, I want to be able to create multiple instances of DList automatically using a for loop kinda like the code below:

for(count=0; count<5; count++) {
DList count = new DList();
}

I had though I would get 5 instances of DList called: 0 1 2 3 and 4.
However, I get a message about count already being assigned.
Can anyone help?
 
Jaime M. Tovar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe in an array:
DList [] dlist = new DList(5);

for(count=0; count<5; count++) {
dlist[count] = new DList();
}

The error you get is because you are using the same variable name twice in the same code segment. count for the 'for' and count for the object instance.
 
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
Hi Andy,

Welcome to JavaRanch!

The specific error message here is telling you that you've already used "count" for the name of an int variable, and you can't reuse it in the same scope for the name of another variable.

But I think what you're trying to invent is called an array. An array is an ordered collection of objects. It has a definite length, and each item in the array has an index, which starts at 0 and is just the position of that item in the array. You can create an array of 5 DList objects like this:



Then you could, for example, print the third DList like this:

System.out.println(dlists[2]);

You can learn more about arrays from your textbook.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jaime Tovar:
Maybe in an array:
DList [] dlist = new DList(5);


That should be
 
andy hough
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
excellent thanks. I'm quite familiar with arrays but to be honest had not even considered using them in this way!
I shall try it out this evening!
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!