Domanda

I want to create a HashSet of my own custom data type. I have implemented my custom data type as an Interface named Pair. Here are the codes I've come up with so far (full of errors of course ;) );

btw, the file Pair.java, containing public class Pair is in the same folder as Names.java; and I'm not using any IDEs, I'm using command prompts in CMD:

file Pair.java:

public class Pair<T1, T2> {
    private T1 firstItem;
    private T2 secoundItem;

    public Pair(T1 first, T2 secound) {
        firstItem = first;
        secoundItem = secound;
    }

    public T1 first() {
        return firstItem;
    }

    public T2 secound() {
        return secoundItem;
    }
}

file Names.java:

import java.util.HashSet;

public class Names {
    public static void main(String[] args) {
        HashSet<Pair<String, Integer>> names = new HashSet<Pair<String, Integer>>();
            names.add(Pair("Name1", 1));
        names.add(Pair("Name2", 2));
        names.add(Pair("Name3", 3));
        names.add(Pair("Name4", 4));
        System.out.println("The number of names is " + names.size());

        for(Pair P : names) {
                System.out.println(P.first() + " : " + P.secound());
        }
    }
}
È stato utile?

Soluzione

Change

names.add(Pair("Name1", 1));

to

names.add(new Pair("Name1", 1));

You need the keyword new every time you create an object.

Altri suggerimenti

You need to call javac with all *.java files. It does not look for other files in the current directory.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top