I have a class with a private static HashSet defined in it that holds objects, when I pass a new object to the class all the elements of the HashSet change to the last inserted objects. I thought a static declared Hashset is only created once so any objects added to it from a instance of the class would stay there

package dao;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import domain.Category;

public class CategoryDAO {

	private static Set<Category> categories = new HashSet<Category>();
	// setter for products
	public void store(Category category){
//System.out.println(categories.toString() +"in array after add");	
	//testing the static hash set
	public void displayHashSet(){
	Object o = categories;

		if(o instanceof Category) {
			Category category = (Category) o;
			System.out.println(category.getName()+"  "+category.getDescription());
	// getter for products
	public Set<Category> getAll(){
		return categories;

A static method implies a class level method (as opposed to the instance methods) while a static variable implies a class variable. All instances of that class would share the same copy of the variable. If you want your 'HashSet' to be 'free from changes', make it final.

Also keep in mind that the Hashset doesn't allow duplicates, if thats what you are looking for...

of course always remember that final only refers to the reference to an object, not the content of that object.
So if you make if final you can't assign a new HashSet to it but you can still change what's stored in it.

This article has been dead for over six months. Start a new discussion instead.