Object conversion [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 9 years ago.
Improve this question
I have list defined as - List iAmAListWithNoGenricType;
Strings are being stored in the list.
I am passing this list to a method which
paramMap = populateMap(list,paramMap);
public Map<Object,Object> populateMap(List list,Map<Object,Object> paramMap){
paramMap.put("key",list);
return paramMap;
Now on doing this hashcodes are being stored in the Map.
key = {#code,#code......}
I tried these :-
List<String> newList = new ArrayList<String>();
for(String item:list){
newList.add(item);
}
and also tried converting a object to string but everything failed.
User iterator as well like this :-
Object element=itr.hasNext();
newList.add((String)element);
Also,
newList.add(item.toString());
But the system crashes.
What is the way out?

First thing, you haven't initialized your list. Secondly, you should provide the exception which you are getting instead of posting "System crashes".
Here, you have got element, which is of type Boolean, as itr.hasNext() returns true OR false based upon if any next element exists in list or not. Then you have used this into sysout where you can get classcastexception. As you can't cast Boolean to String.!
So use hasNext method in this way may help -
while(itr.hasNext()) {
//operation on list like ADD
}

for (Object o : list) {
newList.add((String) o);
}
Note that you shouldn't have a list without a type parameter if at all possible.
In this attempt:
List<String> newList=new ArrayList<String>();
for(String item:list){
newList.add(item);
}
Java seem that the static type of elements of list is Object. You can't assign those to a String variable without a cast, so Java refuses to allow your code.
In this attempt:
Object elemnt=itr.hasNext();
newList.add((String)element);
hasNext doesn't return the next element. It returns true if the list has more elements to iterate over. The boolean it returns gets autoboxed to a Boolean and stored in elemnt, and then the attempt to cast the Boolean to String fails.
In this attempt:
newList.add(item.toString());
toString isn't how you cast something you know is a String to the static type String, but it wouldn't have caused a crash or compile error by itself. You probably had more errors somewhere else.

Object elemnt=itr.hasNext();
newList.add((String)element);
This crashes because Iterator.hasNext() is a boolean. Correct code would be:
while(itr.hasNext())
newList.add((String)itr.next());
Or something like that.

Modify your code as below: No need to pass the map to method, if you want to return the same map from the method.
public Map<Object,Object> populateMap(List list){
Map<Object,Object> paramMap = new HashMap<Object,Object>();
if(list != null & list.size() > 0){
int key = 1;
for(Object obj : list){
paramMap.put(("Key"+key), obj);
key++;
}
}
return paramMap;
}
Call your method like this:
Map<Object,Object> paramMap = populateMap(list);

Related

Adding a String to a StringList while it is part of a hashmap value

Say I have Map<List<String>, List<String>> whatComesNext,
And while in a for loop, for every iteration I want to add the nth element of List<String> text to the value of whatComesNext. Why can I not perform whatComesNext.put(key, whatComesNext.get(key).add(text.get(n)))? The idea would be to retrieve the value from its respective key in the hashmap and add my desired String to it. This is assuming that every key in the hashmap has a value.
Below is my full code:
static void learnFromText(Map<List<String>, List<String>> whatComesNext, List<String> text) {
for (int i=0; i<=text.size()-3; i++) {
if (whatComesNext.containsKey(Arrays.asList(text.get(i),text.get(i+1)))==false) {
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), Arrays.asList(""));
}
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1))).add(text.get(i+2)));
}
}
The Arrays.asList() looks complicated, but it's because I was getting null maps when trying to intialize my own String Lists to try and hold my keys and values, which someone told me was because I was repeatedly clearing the lists that the keys & values were assigned to, leaving them null. I thought I'd solve that problem by referring directly to the original List<String> text, because that remains unchanged. The idea is to first check if a key is not present in the map, and if so assign it an empty List as a value, and then add a String from text to the value of the map.
The error I get when running the code is Error: incompatible types: boolean cannot be converted to java.util.List<java.lang.String> in the line whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1))).add(text.get(i+2)));. I don't understand where this could go wrong, because I don't see which method is returning a boolean.
The error comes from the fact that List.add(Object o) returns a boolean and not the List itself. The Map is declared to contain instances of List<String> as value. If you simply want to add a value to a list, just retrieve it from the map and call add on it. Check the result of the get-process for null and create a new list and put it into the Map if that's the case
I can see a couple of other problems as well:
You call Arrays.asList(...) multiple times creating multiple lists with the same elements. This is a major performance issue and you're just lucky, that the returned list is actually implementing equals, so that your logic is actually working (I expected that to be the problem of your "doesn't work"-description before you updated it.
If the key doesn't exist, you're creating a List containing an empty text. If that should be an empty list, that's not what you're doing and you might run into problems later on, when you work with text-values (that is the empty text as first element) that weren't part of the original input values.
Without changing the type of the key of the Map a - in my eyes - better implementation would look like this:
static void learnFromText(Map<List<String> whatComesNext, List<String>, List<String> text) {
for (int i=0; i<= text.size() - 3; i++) {
List<String> listKey = text.subList(i, i+2);
List<String> value = whatComesNext.get(listKey);
if (value == null) {
value = new ArrayList<>();
whatComesNext.put(listKey, value);
}
value.add(text.get(i+2)));
}
}
The calculation of the list for the keys happens only once, increasing performance and reducing the need of resources. And I think it's more readable that way as well.
The .add() method returns a boolean, your parenthesis are misplaced, replace your last line with this one:
whatComesNext.put(Arrays.asList(text.get(i),text.get(i+1)), whatComesNext.get(Arrays.asList(text.get(i),text.get(i+1)))).add(text.get(i+2));

Implementing a Bag in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm implementing a bag of Integers in java and I'm not sure how to do so. I would like to do so with either a HashMap, LinkedHashMap, TreeMap, TreeSet, or HashSet. Some of the things I'd like to do are
Be able to count the number of occurrences of a certain element (So I cannot use a set)
be able to add without the structure immediately deleting duplicate integers
I've tried implementing a map so far but I run into problems when I try to add to the map because I'm trying to implement a bag of integer objects not key value pairs.
public class Bag<Integer> {
private int count = 0;
private HashMap <T, Integer> map;
//class constructor
public Bag(){
this.map = new HashMap <T, Integer>();
}
would a linked hash set be best? I'd like to add duplicate Integers.
If I read your question correctly, you simply want
Map<Integer, Integer> integerBag = new HashMap<>();
Key: represents the different Integers you have in your bag.
Value: represents the count how often the corresponding key was added.
When adding a "new" Integer, you put(newValue, 1) into the map. When the same number comes in, you increase that counter; and decrease on removal.
Beyond that:
without the structure immediately deleting duplicate integers doesn't make much sense. Integers are just numbers; why would you want to remember "6 6 6" ... when you could remember "I got 6 three times" instead?!
Given your comments:
you don't need to change the signature of your method. The compiler generates code to turn primitive types such as int into their big brothers such as Integer automatically. That is called auto-boxing.
but you can also do that manually.
See here:
int intval =5;
Integer asInteger = Integer.valueOf(intval);
if (Integer bag.contains(asInteger)) {
Just use a HashMap. You might want to count how many duplicates you have:
Map<Whatever, Long> bag = new HashMap<>();
To add an element, use the merge method:
bag.merge(someElement, 1, (oldValue, value) -> oldValue + 1);
And to remove an element, you might want to use the computeIfPresent method:
bag.computeIfPresent(someElement, (key, value) -> (value == 1 ? null : value - 1));
Because of your requirement #2, I don't think you can use any collection based on hashing. If you need to retain duplicate Integers, you'll need to use a List.
Adding a new items is easy, just call add() on the list. Finding all items requires a short loop; to count them just call size() on the resulting list.
The code below is not tested.
public class Bag<T> {
private List<T> items = new ArrayList<>();
public void add( T i ) { items.add(i); }
public List<T> findAll( T target ) {
ArrayList<T> retVal = new ArrayList<>();
for( T i : items ) {
if( i.equals(target) )
retVal.add( i );
}
return retVal;
}
}

Arraylist - how to get a specific element/name? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've tried to search the WWW but failed to find an answer. Couldn't find one here either.
Here's my question:
How do I get a specific name(element?) from a Customer in an ArrayList?
I'm imagining it looks something like this:
ArrayList<Customer> list = new ArrayList();
String name = list.get(2) // which would return the Customer at 2's place.
But what if I want to search for a customer by name, lets say a customer named Alex? How do I do that?
Bonus question: How do I then delete that customer?
As others have said this isn't all that efficient and a HashMap will give you fast lookup. But if you must iterate over the list you would do it like this:
String targetName = "Jane";
Customer result = null;
for (Customer c : list) {
if (targetName.equals(c.getName())) {
result = c;
break;
}
}
If you need to remove an item from a list while iterating over it you need to use an iterator.
String targetName = "Jane";
List<Customer> list = new ArrayList<Customer>();
Iterator<Customer> iter = list.iterator();
while (iter.hasNext()) {
Customer c = iter.next();
if (targetName.equals(c.getName())) {
iter.remove();
break;
}
}
Your are going to have to iterate through your array using something like this in a function call.
void int HasName(string name){
for(int i=0; i < list.size(); i++) {
String s = list.get(i).getName();
//search the string
if(name.equals(s)) {
return i
}
}
return -1
}
If you really need to search by name consider looking into HashMap.
With an ArrayList, you have to loop... If you can, use a Map (HashMap, TreeMap) to quickly find an element.
This works if you always seek by name, for example. (use name as key of the map)
There isn't a way to explicitly do what you want, unless you want to iterate through the whole collection, comparing the desired name to the current one. If you want this type of functionality, you could try a Map such as HashMap.
Implement equals and hashcode for Customer object. Use customer name attribute for this.
Use ArrayList.indexof to find the index of the element. use the remove method in Arraylist to remove the object by index.

Removing item from generic list 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
I need to remove an item from a generic list in java, but I don't know how to do this. If it was a list of int, I would just set it to zero, if it was strings I would set it to null. How can I do this with a generic list, and I can't use an methods of Arraylist or anything like that, I have to write the method myself.
You can remove an individual object instance with List.remove(Object) or you can remove a specific instance from a specific index with List.remove(int). You can also call Iterator.remove() while you iterate the List. So, for example, to remove every item from a List you could do
Iterator<?> iter = list.iterator();
while (iter.hasNext()) {
iter.remove();
}
I would think that if you are implementing a list yourself you should move all elements after the element you are deleting down one position, set the last one to null, and if you are keeping track of the size of your list, reduce this by one. Something like this
public Object remove(int remove_index){
Object temp = list[remove_index];
for(int i=remove_index;i<size-1;i++){
list[i] = list[i+1];
}
list[--size] = null;
return temp;
}
static <T> List<T> remove(List<? extends T> inputList, int removeIndex)
{
List<T> result = new ArrayList<T>( inputList.size() - 1 );
for (int i = 0 ; i < inputList.size() ; i++)
{
if ( i != removeIndex )
{
result.add( inputList.get(i) );
}
}
return result;
}

How do I display the contents of a Linked List in Java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
In Java, I created a linked list class and added a bunch of values. But I don't know how to display those values.
I tried doing the following:
System.out.println(list);
But it printed out some weird values like ADTList# followed by some jibberish.
for(Object o : list){
System.out.println(o);
}
You will have to iterate through all the items in your linked list and print their values, or else, override the toString method for each of your items.
"ADTList#(followed by some jibberish)" is created by the default toString() method. Override this to print something useful. This may require overriding in both the list implementation and the elements.
Assuming that ADTList is your own implementation of a linked list, it's toString method could look something like this:
#Override
public String toString() {
Iterator<Object> i = iterator();
if (! i.hasNext()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Object element = i.next();
sb.append(e == this ? "(this Collection)" : element);
if (! i.hasNext()) {
return sb.append(']').toString();
}
sb.append(", ");
}
}
This has been copied from the JDK's AbstractCollection class, as Christoffer Hammarström mentioned in his comment. It adds characters to make it list-like, e.g. "[x,y,z]" and also handles the list containing itself.
It might also be worth mentioning that the 'gibberish' in the default toString does actually have meaning. It is the name of the class the object is an instance of, and the hexadecimal value of object's hashCode - where the default hashCode(), will represent a memory location.
You have to get an Iterator on that list by invoking iterator(). Then call next() to get the elements until hasNext() returns false.
Iterator<Object> i = list.iterator();
while(i.hasNext())
System.out.print(i.next()+"\t");
You need to iterate it to see the contents.
for(Object obj : list) {
System.out.println(obj);
}
But your Object needs to have .toString() overriden.
You can print each value performing a for each loop on the list :
List<String> list = new LinkedList<>();
//Fill the list
for (String s : list)
System.out.println(s);
If you have created your own implementation of a linked list (any reasons why you would do that?), you also need to override the default behavior of toString() if you want to print the content of the list in a user friendly way.
If you use the LinkedList provided in java.util, then the line of code you show in your question will print as expected.
Override the toString method and write your own implementation to print useful Info About the same.
public String toString(){
System.out.println("*** CONTENTS ***");
for(Object obj: this){
System.out.println(obj);
//May be you will be required to override toString in your custom domain class to make it more useful
}
System.out.println("*** ******** ***");
}

Categories

Resources