0

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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
i3wangyi
  • 2,279
  • 3
  • 15
  • 12

4 Answers4

1

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.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1

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.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

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

masterX244
  • 221
  • 2
  • 11
0

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.

Kick
  • 4,823
  • 3
  • 22
  • 29
  • You should avoid usage of `Hashtable` class. Instead, use `Map` backed by `HashMap`. – Luiggi Mendoza Feb 13 '14 at 21:29
  • Offcource @LuiggiMendoza but OP want HashTable. – Kick Feb 13 '14 at 21:30
  • That doesn't mean you *should* answer with `Hashtable` (note that there's no `HashTable` class, check the T). It's similar to show people how to use a `Vector` when you should use `List` backed by `ArrayList`. More info: http://stackoverflow.com/q/1386275/1065197 – Luiggi Mendoza Feb 13 '14 at 21:33