File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Generic class

Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77

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

Joined: Sep 20, 2010
Posts: 3379
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

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

Joined: Oct 13, 2005
Posts: 36520
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:
subject: Generic class
Similar Threads
Generic and collection SCJP 5.0
Collections and Generics Help
Question about generics
Generics problem
Generics and More Generics...