aspose file tools*
The moose likes Java in General and the fly likes Generic class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic class" Watch "Generic class" New topic
Author

Generic class

Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
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


SCJP 1.4
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

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

Joined: Mar 13, 2007
Posts: 77
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

Joined: Oct 13, 2005
Posts: 39393
    
  28
Where is your "X" class?
Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
The problem is solved. Thank you!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic class