Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic class

 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

This is my source code at the moment:

public class Reihung <Schluessel, E extends Beschluesselt<Schluessel>>{

protected E [] sammlung;

public int suchen (Schluessel suchSchluessel) {
for (int i = 0; i < sammlung.length; i++) {
if (sammlung[i] != null && sammlung[i].getSchluessel() == suchSchluessel)
return i;
}
return -1;
}

public static void main(String[] args) {

//TODO: Sammlung anlegen
}
}

I want to create a collection (sammlung = collection). Thus, the main method is static, but the field sammlung is not static. I need to instantiate an object within the main method. How can I do it?

Regards, Urs
 
Stephan van Hulst
Bartender
Pie
Posts: 5810
61
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Urs,

First of all, you should probably UseCodeTags. It will make it more likely that people are going to help you out.

Now, in order to use your methods, you need an instance of Reihung. First you need to decide what Object you're going to use as a key. If it is a String, you use:
Where X is a subtype of Beschluesselt.

Take notice, Schluessel may be a nice descriptive name, but it is misleading, because it implies it is an existing class or interface. For generic parameters, we use single letter names. A better class declaration would be:
 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I inserted

Then I get the error message: X cannot be resolved to a typ. What do I have to change?

Regards, Urs
 
Campbell Ritchie
Sheriff
Pie
Posts: 48954
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where is your "X" class?
 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is solved. Thank you!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic