Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to use Hashtables? Java

Tags:

java

hash

I have a class named Stored that will hold my Hashtable, which will hold Objects from the Class "Item". I have never used Hashtables before or really know all that much about them, but from my snooping around it seems as if there is a lot of different ways to use them. So my question is, which is the best? And why?

CODE UPDATED

I have in my program this...

public class Store implements Serializable{

Hashtable<String, Item> store = new Hashtable<String, Item>();

}

I have also seen this...

Hashtable<Object> store = new Hashtable<Object>();

Is one better than the other?

Also for reference my Item Class Objects will have 2 strings and an int as variables if that matters at all.

I'm also wondering if these Hashtables should need any constructor or maybe a size initialization? I have seen that in some examples and not in others. As far as I know they increase in size automatically so...whats the point?

EDIT:

I have this in my main...

Store store = new Store();

    Item item1 = new Item();
    item1.setProductName("Paper Towel Roll");
    item1.setBarCode("111222333444");
    item1.setQuantity(1);

    store.put("111222333444", item1);

    Item item2 = new Item();
    item2.setProductName("Paper Towel Roll");
    item2.setBarCode("111222333444");
    item2.setQuantity(1);

    store.put("111222333444", item2);

    Item item3 = new Item();
    item3.setProductName("Paper Towel Roll");
    item3.setBarCode("111222333444");
    item3.setQuantity(1);

    store.put("111222333444", item3);

    Item item4 = new Item();
    item4.setProductName("Paper Towel Roll");
    item4.setBarCode("111222333444");
    item4.setQuantity(1);

    store.put("111222333444", item4);

My put() calls don't work. Why can't I access my HashTable?

like image 603
Sherifftwinkie Avatar asked Nov 29 '25 03:11

Sherifftwinkie


1 Answers

What you see is not related to Hashtables. It is a feature of the language called Generics. It allows you to restrict the type to use with the object you define, without having to créate a new Class.

A typical usage would be

 Hashtable<Integer, Item> store = new Hashtable<Integer, Item>();

That ensures that, in operations that use the type defined by you, only it is accepted if the type matches.

So,

 store.put(1, new Ítem());

would work, but

 store.put(2, new String("Hello world"));

would fail because String is not a subclass of Item.

If you do not use generics, v.g. old style Java

 Hashtable store = new Hashtable();

it would work, but the compiler won't detect any failure with

 store.put(2, new String("Hello world"));

so you lose (usually) useful controls.

like image 142
SJuan76 Avatar answered Nov 30 '25 16:11

SJuan76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!