Simple question, but everytime I google it there are only examples using an ArrayList, and list.indexOf(3), doesn't work on int[] nums = new int[10]. Soo im a little confused.
Here's the real problem. You appear to think that
int[] nums = new int[10]
is defining a List or a list. It isn't. It is an array. The words "list" and "array" are NOT synonymous in the context of Java. So when you Google for "finding an index of an element in a list" ... you don't get any useful hits.
If you use the >>correct<< terms when searching (Google, SO search, anything) you are far more likely to get useful search results.
For example:
How to find index of int array in Java from a given value?
FWIW, if you want a (real) list of integers in Java you declare it like this:
List<Integer> nums = new ArrayList<>();
Notes
You have to use Integer as the type parameter, not int.
You don't need to provide 10 as a parameter. And if you do, it is a hint that tells the ArrayList what the initial capacity of the list should be. (For an array it is the actual size ... and it can't be changed).
If you want to use indexOf(3) on an array you could create a List from it
ArrayList<Integer> myInts = new ArrayList<Integer>(Arrays.asList(array))
and then you can use
myInts.indexOf(3)
Related
So I have come across an issue I do not seem to be able to fix. So lets say I have an int array and want to check whether the array still has space to add a certain element (from 0-∞) or has no space left, which would mean I would need to create a new array.
The issue is that when my int array has a space to store ten values, all of the spaces are filled with 0, so my program thinks that this array is full. And I can not exclude 0 either because the element which I want to add could be 0 aswell.
Any advice?
You are probably using an int[]? The primitive type int can not be null. A very simple solution would be to use the wrapper class Integer.
Integer[] intArray = {null, 0, 10};
You need to keep track of which positions are filled via additional variables. A Java array itself (when created) is initialized with 0-s and it is technically always full.
If you need a dynamically expanding array, my suggestion is to use java.util.List, which is very handy and in most situations can replace a Java array nicely.
A List tutorial is easy to find, here is an example .
And this is how you use it:
import java.util.ArrayList;
import java.util.List;
....
List<String> a = new ArrayList<>();
a.add("Hello");
a.add("World");
System.out.println(a.size());
You can easily convert to a standard array: a.toArray().
If your numbers are always greater or equal 0, you could just set unused numbers to -1.
i have a problem on my implementation of QM Method on java.
I am having a problem with navigating a 2D ArrayList. My goal in the code is by having the first element of ArrayList in being the address and each time another binary is paired up, i will find that address and add the address of the paired binary.
Is there any way to use the indexOf Function in finding the index of the first element in a 2D Array?
Example.
My 2D ArrayList named table is
[4][3][7];[7][4];[8][3];[9];
I want to add int 5 to the the line where [4] is. so my code goes table.get(table.indexOf(4)).add(5) but it keeps saying that the index is -1. Please help thanks
So consider...
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
// populate list
Integer index = myList.indexOf(4);
// index is -1 because 4 is not of type: ArrayList<Integer>
If you need to add values to an ArrayList based on an integer index, I would consider switching to a different container type such as:
HashMap<Integer, ArrayList<Integer>>
The alternative is not using indexOf ... but instead write your own function to loop through 0 to myList.size() looking for myList.get(loopIndex).get(0) = address to be found, then returning the outer ArrayList index where it was found
Problem is I have a text file I need to read that contains chars and I need to construct that into an 2D array internally in a class. But since when I initialize I also have to specify the values like so:
int[] array;
array = new int[] {2, 7, 9};
Since I don't know the size of the array before I read the file, I am able to create one as a member, but as a local one only. As of this, I resorted to using arrayLists, which is not desirable. Am I missing something?
Thanks.
ArrayList would be the best option for this problem because the size of the ArrayList is mutable, meaning that no matter the size of the data, it will always change it's size to match the amount of elements it contains.
Here's more detail on creating and using 2D ArrayLists.
Hope this helps.
List<Integer> array = new ArrayList<>();
array.add(2);
array.add(7);
array.add(9);
OR prior to Java 9:
List<Integer> array = new ArrayList<Integer>(Arrays.asList(2,7,9));
array.add(10);
OR in Java 9:
List<Integer> array = List.of(2,7,9);
I have an sorted array consisting elements (1,1,2,3,3,4). I want to get unique elements from this array and length of the resulting array.
Output array should consists (1,2,3,4) and size = 4.
If you are using Java 8, you can do it in the following way:
Arrays.stream(arr).distinct().toArray();
DEMO
The easiest thing to do here might be to just add your array elements to a sorted set, e.g. TreeSet:
int[] array = new int[] {1, 1, 2, 3, 3, 4};
Set<Integer> set = new TreeSet<>();
for (int num : array) {
set.add(num);
}
This option would make good sense if your code also had a need to work with a set later on at some point.
Is this for homework? If it is, please say so. I'm going to assume it is.
I would traverse the array and use a List to store values that I have already seen. If I come across a value that already appears in my List, I'll skip it. If not, I'll add it. Then I'll convert the list to an array and return it. I'm not going to write it for you because I'm assuming it's homework, but that is the basic idea.
NOTE: If performance is a concern, use a HashMap instead of a List.
I've just created a new array that is one larger than my previous array and I want to copy the values in my first array into my new one. How do I add a new value to the last index of the new array?
This is what I've tried:
public void addTime(double newTime) {
if (numOfTimes == times.length)
increaseSize();
times[numOfTimes] = newTime;
}
I would recommend trying to use an object such as java.util.List rather than raw arrays. Then you can just do:
times.add(newTime) and it handles the sizing for you.
Why not you use System.arraycopy function.
increaseSIze()
{
double [] temp = new double[times.lebgth+1];
System.arrayCopy(times,0,temp,0,times.length);
times=temp;
}
after that you have times array with 1 increased size.
To set a new value to the last index you can do
times[times.length - 1] = newTime;
Array indices go from 0..n-1.
array[array.length - 1] will address the value at the end of the array.
The last item of an array is always at myArray.length - 1. In your case the last element from the times array is times[times.length - 1]. Have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for more information about arrays.
But more importantly: If you're trying to change the capacity of your array, you are most likely using the wrong data structure for the job. Have a look at Oracle's Introduction to Collections (and especially the ArrayList class if you need an array-like index to access elements).
why wouldn't you want a java.util.ArrayList for this requirement? Practically, there won't be a need managing its size. You just simply do this:
List<Double> list = new ArrayList<Double>();
list.add(newTime);
Consider Arrays.copyOf if working with arrays is a constraint:
import java.util.Arrays;
...
private void increaseSize() {
// Allocate new array with an extra trailing element with value 0.0d
this.times = Arrays.copyOf( times, times.length + 1 );
}
...
Note that if you are doing this type array management often and in unpredictable ways, you may want to consider one of the Java Collection Framework classes such as ArrayList. One of the design goals of ArrayList is to administer size management, much like the JVM itself administers memory management.
I've developed an online executable example here.