Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance set in Java?

Java defines a Set interface where contains() is defined as following:

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

The Collection interface defines contains() as following:

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

I need a Java 'instance set' where contains() is based on == and not equals(). In other words, a set of hard instances where two different objects A and B where A.equals(B) could coexist in this same set, since A!=B.

Is such an 'instance set' delivered in Java or in some public library? I can't find anything, but may be someone knows better on SO. If not, I'll implement it. Thanks.

like image 875
Jérôme Verstrynge Avatar asked Sep 05 '11 06:09

Jérôme Verstrynge


People also ask

What is an instance in Java?

Java instances and instance variables Java is a specific class, and a physical manifestation of this class can be called an instance. Instances of a class have the same set of attributes. However, each instance may be different because of what's inside each attribute.

What is instance in Java with example?

Introduction. Instance variables are specific to a particular instance of a class. For example, each time you create a new class object, it will have its copy of the instance variables. Instance variables are the variables that are declared inside the class but outside any method.

How do you create an instance of a set in Java?

keys; String[] keys1 = new String[2]; keys1[0] = "filter1"; keys1[1] = "filter2"; keys = new HashSet<>(Arrays. asList(keys1)); when(ctx. getFilter()). thenReturn(keys);

What is instance of a class?

In class-based programming, objects are created from classes by subroutines called constructors, and destroyed by destructors. An object is an instance of a class, and may be called a class instance or class object; instantiation is then also known as construction.


2 Answers

There is no direct "instance set" in the JRE.

But there is an IdentityHashMap, which implements a "instance map" according to your terminology.

And there is a method called Collections.newSetFromMap() which can create a Set from an arbitrary Map implementation.

So you can easily build your own instance set like this:

Set<MyType> instanceSet = Collections.newSetFromMap(new IdentityHashMap<MyType,Boolean>());
like image 198
Joachim Sauer Avatar answered Oct 06 '22 23:10

Joachim Sauer


You could just implement the equals method like that:

public boolean equals(Obect o) {
    return this == o;
}
like image 41
dacwe Avatar answered Oct 06 '22 21:10

dacwe