Collections.emptySet() vs new HashSet<>() [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I validate if the Set is empty set or new HashSet<>() ?
Tried two approaches -
size
CollectionUtils.isEmpty()
Both result in same value.

Of course, a fresh new HashSet<>() is empty, and so is Set.of() or Collections.emptySet(). The point is: Both are empty sets, I have no idea why you would want to tell the difference between these two.
The one difference is that new HashSet<>() is empty now but may not be empty later (it can be changed; you can add things to it), whereas as per the spec, the result of Set.of() or Collections.emptySet(), they are empty now and will be empty later: You can't add anything to them, calling .add on them will cause a runtime exception.
That's tantamount to asking: How do I know if it is immutable. You unfortunately basically can't, so that goes right back to: Why would you need to know?

Collections.emptySet() returns a static class EmptySetwithin java.util.Collections but new HashSet<>() returns a java.util.HashSet class. Both collections will be empty, i.e., size = 0 after instantiated but you can distinguish those two by calling .getClass() which will return:
class java.util.Collections$EmptySet
class java.util.HashSet

Use .getClass to see the different implementation that was used.

I got one utility method that can be used to perform the operation -
Collections.EMPTY_SET.equals(mySet)
Thanks all for your answers.

Related

Caching enum values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have more enums with some values and I want asked you what the method is good to cache enum values:
For example:
public enum Animal {
Dog, Cat, Cow;
static Animal[] values;
static EnumSet<Animal> cachedAnimalsEnumSet;
static List<Animal> cachedAnimalsList;
static {
values = values();
cachedAnimalsEnumSet = EnumSet.allOf(Animal.class);
cachedAnimalsList = Arrays.asList(Animal.values());
}
}
Which is the best way:
values, cachedAnimalsEnumSet or cachedAnimalsList ?
Assuming that your purpose of caching is to avoid creation of new array every time anyone calls Animal.values(), and instead just use the cached value. I'd recommend using EnumSet for following reasons:
All basic operations are constant time.
There is not point in caching duplicate enum values, and the Set implementation takes care of it for you.
However, couple things to consider are that null values are not allowed in EnumSet (highly doubt you want to cache nulls). And second thing to be careful about is that EnumSet is not synchronized. So if you are going to have multiple threads access, and modify this cache, you'd have to wrap it using Collections.synchronizedSet method.

Java 1.7 HashMap Integer Key [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm using an HashMap<Integer, MyObject> collection to store a list of few couples of values.
Is it safe use Integer as key? the behavior is the same both on put and get method?
yes it's safe. Integer is just a wrapper class for int.
i know this from own experience. created a captcha functionality that way. (user requests a random integer. my prog creates a captcha-pic and saves the answer[value] and random integer id[key] in a hashmap. btw if you want to create a "cache" use java's LinkedHashMap. it has a protected boolean method called "removeEldestEntry(Map.Entry eldest)" which is called during a put-event. if you override it with, eg "return size() > MAX_SIZE;" it will delete the oldest entry (or the entry based on oldest access - there's an option in the constructor) if the condition you provided returns true). hope this helped. :/

How to create a copy of an arbitrary object in C# or Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose I need to create a multi-set data structure with operations such as intersect and union of two sets. With c# or java.
In both cases I need create a copy of every object of both sets, otherwise changing one of it could break other sets.
I see one solution: specify generic type, for example
class MultiSet<T, U> where T : struct, where U : ICloneable
or something like this in java.
Are there another ways to solve this?
In both cases I need create a copy of every object of both sets, otherwise changing one of it could break other sets
If you want an intersect of two collections of objects, you will want references to those that "match" as a result, rather than copies of them. The latter makes no sense.
To check wether two objects are the same (in set 1 and set 2), just compare them in a meaningful way (i.e. overriding their hash code and compare methods).
The structure of your result collection will also depend on wether or not the objects can be equal to each other without their reference being equal. In that case, the resulting collection will need to hold two references (two for each "match"), one for each set.
As for the union, just simply create one collection that holds references to all the objects in both collections.
Complete side note
Union and intersect are data operations, and so I assume your collections will hold data. It's not the best idea to do such operations in a programming language. There are other tools that are much more up to the task, such as SQL.
Other than the recommended ICloneable? (I say the recommended way, however cloning is usually seen as bad)
I suppose if the objects are Serializable you could serialize and de-serialise as a new object.
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, yourObject);
stream.Seek(0, SeekOrigin.Begin);
return (YourObjectType)formatter.Deserialize(stream);
}
Add a null check and it would make a nice extension method for serialisable objects.
Once again though, cloning probably is not a good solution for your problem, but I don't know enough about your use-case to recommend anything.

Java book was unclear on these two topics [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The basic components of a class:
Is that they can be thought of as templates from which objects can be made?
Three things you can assign to a numeric variable:
Are they: Constants, numbers other variables.
Thanks! I'm trying to pick up the basics, but these two topics from my book have no clear cut answer just a header with an example.
1)I think you have the right idea, but really bad terminology. A class is an object that consists of some data and some code. You can create an instance of a class (called instantiating the class). Each instance has its own copy of all non-static variables in the class.
2)You can assign a number to a numeric variable. Yes, that number could be a constant, another variable, or some mathematical combination of other variables (like x+y, or 5+10, or 15*z). Or a numeric result of a function (say Math.max(x,y) which returns the bigger of x and y).

LinkedHashMap order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is order still guaranteed when the map objects are accessed as shown below at location 1 and 2?
//....
public void firstMethod(){
Map<K,V> sortedMap=new LinkedHashMap<K,V>();
sortedMap.put(h,g);
//....
Map<K,V> anotherMap=someOtherMethod(sortedMap);
// order of anotherMap when read ...2
}
public Map<K,V> someOtherMethod(Map<K,V> someMap){
someMap.put(a,b);
//order of someMap when read ...1
//.....
return someMap;
}
//....
If the concrete instance of your Map object is a LinkedHashMap yes. It does not matter what you do with it. The object will keep it's data ordered and the implementation does not change if you cast to just Map or even Object or pass it to methods. It will stay internally a LinkedHashMap. You might no longer see that it is one if you cast it to Object.
Assuming that you don't know the source code, the only thing that is not guaranteed is that someOtherMethod returns your LinkedHashMap. It could also re-order it.
A method should not be trusted unless it specifies those things. But since you know the sourcecode here, you have the guarantee that it is your LinkedHashMap in perferct order.
As per the docs:
Hash table and linked list implementation of the Map interface, with predictable iteration order.
So even after things are inserted and removed, the order should persist through whatever you want to do to it.

Categories

Resources