Cannot Create an LinkedList<String, int> - java

i want to create an LinkedList of couple that the key is a String and the value is an integer ?

LinkedList doesn't have a key. It's a list of elements, not a key/value mapping.
If you want a LinkedList where each element is a pair of Integer/String values, you'll need to pick one of:
Create a generic Pair class
(Ab)use an existing generic class (e.g. Map.Entry)
Create a custom class for your specific scenario
I would suggest the last option as the most sensible one - you'll be able to give it appropriate semantics and names according to the real meaning of the string and the integer. Heck, you'll also be able to avoid boxing the integer, as you can have:
public class WhateverYouCallIt {
private final int firstValue;
private final String secondValue;
// Constructor, properties
}

You can only use Object in a LinkedList., this means you cant use Java Primitives.
However, what you seem to need is a Map structure.
I recommend using java.util.HashMap, it allows you to create a Key, Value pairs.
Example:
HashMap<String,Integer> a = new HashMap<String,Integer>();
a.put("one",1);
a.put("two",2);
System.out.println(a.get("one"));
//prints 1
System.out.println(a.get("two"));
//prints 2
EDIT:
As per your comment, i see you required order, use the following example then:
LinkedHashMap<String, Integer> b = new LinkedHashMap<String,Integer>();
b.put("one",1);
b.put("two",2);
b.put("a",3);
for (String key:b.keySet())
{
System.out.println(b.get(key)); // print 1 then 2 finally 3
}
Hope this is what you were asking (if so, modify your question).

One error is you need Integer instead of int, but as others have pointed out LinkedList doesn't take Key/Value pairs.

I'd imagine a HashMap is what your after. As other have stated, you cannot use a primitive type such as "int" in a library storage class like LinkedList, or ArrayList, you must instead use an object such as "Integer".
HashMap hash = new HashMap();
Read this for more information: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html

Related

Void Class in HashMap as a Value object

I know the basic that a HasMap is a Key-Value pair but I want to have a HashMap with keys only(No Values)
I want to put below java snippet in my complex method(i.e HashMap with only Keys and no value associated to those Keys). My requirement is that i am processing a List of Duplicate Records, and during comparisons, I am keeping only one identifier value(from group of duplicates) in a HasMap which I can later compare that whether the system has already processed it or not.
Here is the code snippet(gives Compile time error as Void class is uninstantiable).
Map<Integer,Void> map=new HashMap<Integer, Void>();
//Some Logic goes here
map.put("ss",new Void());
Any suggestion/help to have a HasMap only Keys with no value are welcome.
Normally you would use a Set for such an issue, because there is no need to have a Key-Value structure when not using the value at all.
Correct Solution
Set<String> uniqueValues = new HashSet<String>();
uniqueValues.add( "a" );
uniqueValues.add( "a" );
assert uniqueValues.size() == 1;
Note this is just for completeness I would always use a Set for your requirement and the rest is more for fun/learning/confuse people:
Since Void has a private constructor so you can not create an instance with the new Keyword.
However there are at least two possibilities to put something in your Map.
Solution one is to add null as value. Because you do not need it anyway. And the second one would use reflection to ignore the private constructor of the Void class.
HACK SOLUTION
Map<String, Void> map = new HashMap<String,Void>();
Constructor<Void> constructor= (Constructor<Void>) Void.class.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Void voidObj = constructor.newInstance();
map.put( "a", voidObj );
map.put( "a", voidObj );
assert map.size() == 1;
If I understand correctly you want a list where you can add keys but it should not allow to add duplicate keys. Then the solution is to use a Set(Oracle Documentation):
Set<Integer> mySet = new TreeSet<Integer>();
Java also provides a Hashset(Oracle Documentation)
Set<Integer> mySet = new HashSet<Integer>();
You may also need you own Comparator.
Why not just use another list? If you really need to use a HashMap for whatever reason, you can just add null values instead of void.
Map<Integer,Object> map=new HashMap<Integer, Object>();
map.put("ss", null);
Please do not do this. A HashMap is a Map which is a Key-Value-pair. A Map without values is not a Map.
If you want to store values without duplicates use a Set - a HashSet for example.
First of all the constructor of Void class is private, so the compiler will mark new Void() as error. Next, to prevent duplicates, you could just use a Set . Why not go with HashSet?.
Here's what javadoc says about Void -->
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.

Confusing Java data structure - static HashMap of own class

I am a Java beginner. Recently I try to study the Java code of my company system and I come up with a very confusing data structure. It is a static variable of HashMap, but the HashMap is type of it class...
This is the example.
public class CustomerList{
static ByteHashMap<CustomerList> Element1 = new HashMap<CustomerList>();
static ByteHashMap<CustomerList> Element2 = new HashMap<CustomerList>();
static ByteHashMap<List<CustomerList>> Element1 = new HashMap<List<CustomerList>>();
....
}
Can anyone explain to me the purpose of this kind of data structure? And in what perspective should I understand this data structure?
edit: The ByteHashMap is come from a open source library
I doubt what you published is valid code because Map or HashMap takes 2 parameter types i.e. Map<K, V>.
If you are actually asking about the practice to set a static structure of its own type on the class level, then yes its OK. It's a convenient way to keep a global collection of a certain class. One sample usage is when you want to ensure == equality when object equals and to return the unique instance.
In first example of HashMap, we will create and add object into our Map. Always use Generics, if you are not working in Java 1.4. Following code will create HashMap with keys of type String and values of type Integer with default size and load factor.
HashMap<String, Integer> cache = new HashMap<String, Integer>();
alternatively you can create HashMap from copying data from another Map or Hashtable as shown in below example:
Hashtable<Integer, String> source = new Hashtable<Integer,String>();
HashMap<Integer, String> map = new HashMap(source);
You can also supply load factor (percentage of size, which if fulled trigger resize of HashMap) and initialiCapacity while creating instance by using overloaded constructor provided in API. Adding elements, also called put operation, requires key and value object. Here is an example of adding key and value in Java HashMap:
map.put(21, "Twenty One");
map.put(21.0, "Twenty One"); //this will throw compiler error because 21.0 is not integer
for more details please refer
http://java67.blogspot.in/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html

Can I define a hashmap differently to it's declaration

What I would like to do is have a map that actually holds values as one thing, but is declared as another e.g. actually hold the value as String, but put/get will use Integer...
Map<String,String> map = new HashMap<String,String>();
I can use this map with
map.put("A","1");
String ret = map.get("A");
but this will get me a String, and I need to 'put' in a String too.
What I would like is for the put/get methods to accept an Integer value (but the map still stores ...
map.put("A",1);
Integer ret = map.get("A");
How can I achieve this?
N.B. this isn't exclusively for String/Integer conversion, but just conversion between any types.
Thanks.
You can use Object as the value type. It can store String, Integer, Double, for that matter almost anything. But you need to be very careful when using Object because you'll have to cast each value you get from the map accordingly(else you'll always get a ClassCastException).
Map<String, Object> map = new HashMap<String, Object>();
FYI, I do not recommended you to use this. Instead be sure what your Map has to hold and have the value type accordingly.
Simply
Map<String,Integer> map = new HashMap<String,Integer>();
You can (but not SHOULD use, really) this critter: https://gist.github.com/eltabo/8953176. Really... it's evil.
Only for educational purpose.
Why should someone want to store a value in a different representation than the value is made out of? You still can create a string out of an integer and reverse after obtaining it from the map, but what is your advantage?

How to initiate multidimensional arraylist with different objects?

I'm having trouble trying to initiate an arraylist in which the first column I want to be a string, and the second column be a custom object.
For example column [0] be String, and column[1] be an Integer. Convention attempts of creating a multidimensional arraylist as in those used by int[][] or String[][] don't seem to work :( I would welcome any help. At this point I don't think it's something java allows. I can make it work for just one type of object but it's not what I want. Thanks!
Do you need an arraylist? You could create a Map<String, Object> or Map<String, Integer> or whatever you need..
Sure it does, but you weaken/eliminate type-checking:
Map myMap<String>, Integer> myData = new HashMap<String, Integer>();
Now your list of strings can be retrieved by myMap.keySet() and values can be retrieved by myMap.values(). Each of these return a Set, which you can easily convert to a List using the following code:
List<String> strings = new ArrayList<String>(myMap.keySet()); // get your strings
List<Integer> numbers = new ArrayList<Integer>(myMap.values(); // get your numbers
Good luck and if you should run into problems, do leave a comment.
Arrays are geared towards one specific type of thing - be they Object or String or int. Despite the fact that you're adding multiple dimensions to them, they still only hold one type of information.
What you would rather have is a mapping between two objects. This allows you to do the following:
Associate any key to a particular value
Eliminate duplicate key entries
Be much easier to access instead of array indexing
Here's an example. Say your custom object is a Cat, and you want to map the name of the owner to a particular Cat. You create a new instance of a Map.
Map<String, Cat> catOwners = new HashMap<>();
You can then put elements into it...
catOwners.put("Jamie", new Cat("Tycho"));
...and retrieve them with relative ease.
Cat currentCat = catOwners.get("Jamie"); // gets Jamie's cat
if you really want to, you can even iterate over them using the Map.Entry object provided with all Maps:
for(Map.Entry<String, Cat> element : catOwners.entrySet()) {
System.out.println(element.getKey()
+ " owns " + element.getValue().getName());
}
What you can do is use the generic Object type, and cast accordingly.

How to put Objects from one map to another?

I have a Map like this :
Map<String,GridCell> cellsMap
I pass this into a method and the return from that method should contain a Map(say answerMap) which contains all the entries of cellsMap map plus an extra entry that contains a String as the key and a String as the value . Something like :
Map<String,Object> answerMap = new ConcurrentHashMap<String,Object>();
//answer should first contain all the map entries of cellsMap and then add an extra entry like the following
answer.put(getId(), getSelectionValue()); // getSelectionValue() returns a String that contains coordinates of the selected cells.
return answerMap;
Have you considered the Map.putAll() method ?
e.g.
answerMap.putAll(cellsMap);
I don't think this is a good object model, by the way. I think you're better off creating a new class that contains your original map (maybe a copy) and an additional field for your String/String pair.
Otherwise you're throwing objects of different types into the same map, and that's going to make life complicated when you later extract that info. Each time you extract via a key you're going to have to check the type of the object returned. Note that ConcurrentHashMaps don't maintain insertion order.
Use clone() method.
HashMap answerMap = (HashMap)cellsMap.clone();
Map interface has putall() method which add all values of another object in Map.

Categories

Resources