This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 3602

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: 38046
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
Generics problem
Question about generics
Generic and collection SCJP 5.0
Generics and More Generics...
Collections and Generics Help