简体   繁体   中英

Can we create a pair (a,b) as values in Hashtable in Java

I'm kind of freshmen in Java. I learned hashtable might help me solve a problem.

I want to create a Hashtable such that every entry of it is a key-value pair of

<Float, (a,b) >

And every entry contains a linkedlist of many pairs, how can I write codes to implement that?

You can use a Point to represent a pair of points, or alternatively your own class with 2 int or double entries. The advantageTof using your own class to wrap and hold the two values together is that it can be as simple and specific to your needs. In any case, those would be your values in the HashTable.

First, create a Pair class:

//A and B are generics
class Pair<A, B> {
    private A element1;
    private B element2;
    public Pair(A element1, B element2) {
        this.element1 = element1;
        this.element2 = element2;
    }
    //public getters...
}

Second, have a Map<Float, List<Pair<A, B>>> to insert your key/value:

Map<Float, List<Pair<A, B>>> table = new HashMap<Float, List<Pair<A, B>>>();

Third, create a List<Pair<A, B>> backed by LinkedList<Pair<A, B>> :

List<Pair<A, B>> myList = new LinkedList<Pair<A, B>>();

Fourth, add your list into your map.

table.put(1, myList);

You should not use LinkedList nor HashMap classes directly, instead try to code oriented to interfaces . Also, I would recommend you to use another key instead Float or Double since their values may differ due to floating point comparison . I would recommend Integer , Long , String or BigDecimal instead of Float .

the value entry of HashMap can be any Object and a LinkedList is a object so

HashMap<typeofkey,LinkedListy<Typeofvalueobject> map = new HashMap<>();

just replace the typeofkey and typeofvalue with approbiate types

The object will be as below :

HashTable<Object,LinkedList<Object>> obj = new HashTable<Object,LinkedList<Object>>();

And to add the element just use put method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM