difference between TreeSets based on their interface [duplicate] - java

This question already has answers here:
What is the difference between a variable, object, and reference? [duplicate]
(5 answers)
Closed 6 years ago.
Is there any difference between the two TreeSets ?:
Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();

Difference is s have acccess to method shared by s type (if you don't cast it). But the object real type is the same.

Calling new HashSet<String>() will always create an empty HashSet. While these are all different instances, they are equal, regardless of whether you assign them to a HashSet, a Set or even a plain old Object.
Note, however, that HashSet is not a SortedSet, and the second statement in the question will cause a compilation error.

Only their apparent type is different. Since their real type is the same, their behavior will be identical.
It's similar to:
Integer i = 42;
Object o = i;
String s1 = i.toString(); // "42"
String s2 = o.toString(); // "42"

Related

referring to this only (not attributes), possible? [duplicate]

This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 1 year ago.
Context (not strictly necessary to understand the question):
I have to implement a collection of elements. The class is called DocumentCollection. It is essentially an array of lists (a rudimentary form of a hash array), better formulated: an array of references to the first element of each respective list.
I already implemented a basic constructor, which takes an int as size of the array, and puts null initialized lists in each bucket.
One method to implement is removeAll. My first idea was to generate a new collection of the same size as the original one, and assign this to this newly created collection.
Below the code of the method.
public boolean removeAll(){
if(isEmpty()){
return false;
}
int size = buckets.length;
this = new DocumentCollection(size);
return true;
}
where buckets is the array.
As this is part of an assignment, I don't want to include the code of the whole class. This is enough for my question.
Intellij gives me the following error message (w.r.t. the line with this): variable expected.
Unfortunately this message is not eloquent enough for me to understand it.
Aside Note: yes, I could iterate over the array and assign null lists to them. That's not the point I am trying to make here
Question:
Am I doing something fundamentally wrong? In other words, is trying to give a new reference to the current object (i.e. this) illegal? Or can it be done, and I am simply using some wrong syntax?
You can't assign a new value to this since it is just a keyword to represent the current object along the class code, it is not a variable.
Beside's that, think of the semantics: you are inside the object asking it to become another object, that would be very tricky!
The closest you can get to that is to wrap some object as a field of your class, then you can assign a new instance to this field. Like this:
class MyObjectWrapper{
private MyObject myObject = new MyObject();
...
public void removeAll() {
this.myObject = new MyObject();
}
}
Check this related question: Why is assignment to 'this' not allowed in java?

Hashset Containg duplicate values ; Also ArrayList indexOf(string_present_in_list) returning -1 [duplicate]

This question already has answers here:
A Set in java never allows duplicates, but it takes StringBuffer objects with the same argument. Why?
(6 answers)
String Vs Stringbuffer as HashMap key
(4 answers)
Can a StringBuffer be used as a key in a HashMap?
(4 answers)
Closed 5 years ago.
I have made a Hashset of StringBuilder.
The below code returns "true" even if that StringBuilder is present in Hashset:
if(!contains(sb_obj))
{
...
}
Also I have made a ArrayList of StringBuilder.
The below code returns "-1" even if ArrayList contains obj:
if(arr.indexOf(obj)==-1)
{
....
}
Why such behaviour?
I assume you are comparing different StringBuilder objects that have the same String values.
StringBuilder doesn't override equals and hashCode methods. This causes HashSet and ArrayList to use Object's implementation of them which compares by identity. Since you are comparing different objects they are different.
Please use String instead of storing StringBuilder object or if you want to store custom object override hashcode and equals methods whenever you are trying to add and search back that object.
Please read the concept of hascode and equals method, you can find many examples over internet.

Difference between c.toArray(new String[size]) and c.toArray(new String[] {}) [duplicate]

This question already has answers here:
.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
(8 answers)
Closed 7 years ago.
I can't seem to find an explanation for this. Does new String[] {}
provide a more efficient way of providing the type of array?
new String[] {} is an empty array, which means toArray would have to create a new String array in order to convert the Collection to an array (unless the Collection is empty, in which case toArray can simply return the empty array that was passed to it).
In most cases c.toArray(new String[c.size()]), which passes the array instance that would be returned by the method, would be slightly more efficient, since one less array object is instantiated compared to c.toArray(new String[] {}).

Object equality(object referece "==") [duplicate]

This question already has answers here:
What is the Java string pool and how is "s" different from new String("s")? [duplicate]
(5 answers)
Closed 8 years ago.
I have written this code in eclipse:
String[] s = {"a","b"};
String d = "a";
System.out.println(s[0]==d);
and it is giving "true" as output.
"==" checks for object reference, if both object refer to same object, but here in this case object "d" refers to different object and "s[0]" to different, then how come they are equal.
"a" will have been created in the string pool used by the JVM.
As an optimisation only one instance of that string will have been created. Java can do this since strings are immutable. That's why the references are referencing the same underlying object, so in this particular instances, the references compare equal.

Object Creation JAVA [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between “text” and new String(“text”) in Java?
Please explain the brief and detailed difference between following 2 statements:
String a= "somevalue";
String b = new String("somevalue");
I know that 2nd statement creates and provide memory to String Object b in heap. But why object a doesn't get memory and its still allowed to operate on string methods.
a and b are references to Objects, not Objects.
When you do a = b; it doesn't copy the Object, it copies a reference to an Object.
A String has a char[] inside it which is another object.
a gets an reference to an existing object so it may not need any extra memory.
b get a reference to a newly created object so that requires more memory.
its still allowed to operate on string methods.
This has nothing to do with how the object was created.
The first affects the literal String object "somvalue" to variable a. This literal String object is cached in a pool, as all literal Strings.
The second creates a new instance of empty String. Since String instances are immutable, it's equivalent to String b = "";, except it instantiates a new object for nothing.

Categories