Hey i have an array list of numbers and when i try to convert into int i get The method intValue() is undefined for the type Object error. This is the code snippet.
while (1>0) {
a = Integer.parseInt(in.next());
if(a == -999)
break;
else {
list.add(a);
i++;
}
}
int j;
int[] array = new int[list.size()];
for(j=0;j<list.size();j++) {
array[j] = list.get(j).intValue();
}
It seems you have created a list of objects and not Integers. Hence when you call intValue then it says that there is no such method for type Object. I would recommend that you define your list as list of Integers using generics. Here is the sample:
List<Integer> list = new ArrayList<Integer>();
If you don't do so then you list created will hold the items of class Object. And then you need to cast the object fetched from the list everytime to Integer.
Related
So, this is part of a method which checks for available rooms within a date range and is meant to return the int [] array of room numbers which are available.
ArrayList roomNums = new ArrayList();
roomNums.toArray();
for (Room room: rooms){
int roomNumber = room.getRoomNumber();
if(room.getRoomType() == roomType && isAvailable(roomNumber, checkin, checkout)){ // This works fine, ignore it
roomNums.add(roomNumber);
}
}
return roomNums.toArray(); // Error here, return meant to be int [] type but it's java.lang.Obeject []
The error occurs at the end at roomNums.toArray()
I saw someone else do this one liner and it worked for them, why is it not for me?
Every element in roomNums is an integer. (I think)
What's the quickest and easiest way to print an integer array containing the available rooms? Do I need to make a loop or can I do something with this .toArray() one liner or something similar to it?
Thanks
Don't use raw types. Replace ArrayList roomNums = new ArrayList(); with
ArrayList<Integer> roomNums = new ArrayList<>();
Then return it as Integer[]
roomNums.toArray(Integer[]::new);
If you need primitive array, then it can be done with stream:
return roomNums.stream().mapToInt(Integer::valueOf).toArray();
See also How to convert an ArrayList containing Integers to primitive int array?
Unfortunately, you will need to use Integer[] if you want to use toArray
List<Integer> roomNums = new ArrayList<>();
// code here
Integer[] arr = new Integer[roomNums.size()];
return roomNums.toArray (arr);
However you can still do it manually like
List<Integer> roomNums = new ArrayList<> ();
// code here
int[] arr = new int[roomNums.size()];
for (int i = 0; i < arr.length; i++)
arr[i] = roomNums.get (i);
return arr;
As mentioned above use the ArrayList to hold your values:
ArrayList<Integer> roomNums = new ArrayList<>();
then you can use the object super class to convert to array
Object[] numbersArray = roomNums.toArray();
then just continue running the for loop and your program
private static <T> void shuffle(T[] array){
if(array==null || array.length < 2){
return;
}
for(int i=1;i<array.length;i++){
int a = rng.nextInt(i+1);
System.out.println(a);
T temp = array[a];
System.out.println(temp);
array[a] = array[i];
array[i] = temp;
}
}
static boolean checkSorted(ISort sorter, int size) {
Integer[] data = new Integer[size];
shuffle(data);
}
This the output when printing the variables a and temp:
0
null
2
null
0
null
2
null
0
null
4
null
7
null
8
null
6
I'm not sure why temp is null instead of Integer. Can anyone explain this to me? How should I modify this code in order to make it work?
Integer[] data = new Integer[size]; is an array of Integers, but until assigned all members in array are null, which you are printing. Initialize the array properly first:
Integer[] array = new Integer[5];
array[0]= new Integer(0);
array[1]= new Integer(1);
In Java, every variable has a type. When you declare a variable without specifying a value, it will have, by default, a predefined value. If it's a variable that contains a reference to an Object (in other words, a variable of a composite type) it will have null as it's value. On the other hand, if it's a variable of a primitive type, it will have different values according to it's type (default value for numbers is 0). See the table below for more details.
(image taken from the Java's docs, here)
With this in mind, we can now proceed to your code's behaviour. When you create an array of the type Integer, all of it's elements will be null by default. Note that Integer is an object wrapper class (see type wrappers), while int is a primitive type. If you had created an array of the type int, all it's elements would have, by default, the value 0. That's why when you print temp null is being printed, and not a number. To solve that, you can assign values to the array's elements, like below:
Integer[] data = new Integer[size];
Random random = new Random();
for(Integer i: data) {
i = random.nextInt(100); //assign a random value between 0 to 99
}
This question already has answers here:
Convert list to array in Java [duplicate]
(11 answers)
Closed 8 years ago.
I have a created a LinkedList with an Employee object stored in it. I need to write a method convertToArray that would make an array of Employees by taking it from the LinkedList.
Any ideas?
The easiest way to do this is to utilize LinkedList.toArray method
// create an array and copy the list to it
Employee[] array = list.toArray(new Employee[list.size()]);
However, if you are just learning and would like to do this iteratively. Think about how you would declare and get all of the items into an array.
First, what do you need to do?
1) Declare the array of Employee's
In order to do that, you to know how big to make the array since the size of an array cannot be changed after declaration. There is a method inherited from List called .size()
Employee[] array = new Employee[list.size()]
2) For each slot in the array, copy the corresponding element in the list
To do this, you need to utilize a for loop
for(int i = 0; i < array.length; i++) {
//access element from list, assign it to array[i]
}
public <T> T[] convert (List<T> list) {
if(list.size() == 0 ) {
return null;
}
T[] array = (T[])Array.newInstance(list.get(0).getClass(), list.size());
for (int i=0;i<list.size();i++) {
array[i] = list.get(i);
}
return array;
}
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
arr[i] = e;
i++;
}
I need to use an ArrayList, but I am not sure how to do some of these things that would be possible with a normal array.
1) This:
int[][] example1 = new int[10][20];
(An array with two arguments (10, 20)) is possible with normal arrays, but how to do it with an ArrayList.)
2) How to increase the value of an int on the list by 1, like this:
example2[3][4] ++;
ArrayList is dynamically growable list backed by array.
List<List<Integer>> list = new ArrayList<List<>>(10);
you can get an element of list by List#get.
List<Integer> innerList = list.get(3);
Integer integer = innerList.get(4);
Update value by List#set -
list.get(3).set(4,list.get(3).get(4)++);
NOTE : Integer class is immutable.
To mimic a multidimensional array using collections you would use:
List<List<Integer>> list = new ArrayList<>(); //Java 7
List<List<Integer>> list = new ArrayList<List<Integer>>(); //Pre Java 7
So lets say we create a List<List<Integer>> where the outer List contains 10 List<Integer> and the inner list contains 10 Integers. To set the fifth element on the fourth list:
public static void main(String[] args) {
List<List<Integer>> outer = new ArrayList<List<Integer>>();
for(int x = 0; x < 10; x++){
List<Integer> inner = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
outer.add(inner);
}
//Remember that Integer is immutable
outer.get(3).set(4, new Integer(outer.get(3).get(4)) + 1);
}
int[][] example1 = new int[10][20]; you can do it in arraylist by using this syntax :
ArrayList<ArrayList<Integer>> ex = new ArrayList<ArrayList<Integer>>();
example2[3][4] ++; This can be same in arraylist as by using this :
int val = (a.get(0).get(0)) + 1;
The equivalent of your declaration with an ArrayList is:
List<List<Integer>> example1 = new ArrayList<>();
You have to use Integer because Java Collections do not support primitive types. Check out this page of the Oracle docs for more information on Autoboxing and Unboxing.
Since an ArrayListcan grow dynamically, you don't need to give a size. If you want it to have an initial size, you can pass that as an argument to the constructor.
You can get elements from an ArrayList (or any Class implementing the List interface) by using the get() method with the index of the element as an argument.
Using example.get() on example1 will give you an object of the type List. You can then use get() again to get an Integer.
I have loaded the contents of the database in an ArrayList named countList. The contents loaded are of int type. I created countList using the command
ArrayList countList = new ArrayList();
Now, I need to check if each contents of the arraylist is greater than three. I wrote it like
for(int i=0; i< itemset.size(); i++){
if(countList.get(i) >= 3)
{
}
}
When I write it simply, it shows error of bad operand type for binary operator '>='. How to do the task?
The >= operator is only defined on number types such as int, double or Integer, Double. Now, countlist may well contain integers (I assume it does), but the way you have written your code, the compiler can't be sure. This is because an ArrayList can store any type of object, including but not necessarily Integer. There are a couple of ways you can remedy this:
a) You can cast the ArrayList item to an Integer, at which point the >= operator will work:
if ( (Integer) countList.get(i) >= 3)
b) You can use generics to tell the compiler that your ArrayList will ONLY store Integers:
ArrayList<Integer> countList = new ArrayList<Integer>();
for(i=0; i< itemset.size(); i++){
if (itemset.get(i) > 3) {
// Do whatever you want here
}
}