Changing Array to ArrayList [duplicate] - java

This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}

There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.

Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case

An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...

Related

Take out sub set of indexes from array of type integer [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 1 year ago.
So I have a List in which there are say 2 elements (suppose [1,2]), now the return type of method is int[] so I need to convert this Listto int[].
Here is my so far code,
public int[] twoSum(int[] nums, int target) {
List<Integer> l1 = new ArrayList<Integer>();
int lengthOfnums = nums.length;
int[] indexOfNums = new int[nums.length];
if(lengthOfnums != 0)
{
for(int i=0; i <=lengthOfnums-1; i++)
{
for(int j =1; j<=lengthOfnums-1;j++)
{
if(nums[i] + nums[j] ==target)
{
//l1.add(i);
//l1.add(j);
indexOfNums[i]=i;
indexOfNums[i+1]=j; // here somewhere logic goes boom
}
}
}
}
return indexOfNums;
}
When I use (to operate on l1 arrayList)
Integer[] boxed = l1.stream().filter(Objects::nonNull).toArray(Integer[]::new);
indexOfNums = ArrayUtils.toPrimitive(boxed);
It gives output something like - [I#6bf2d08e, I think it is something related to address of memory, (not sure on this part).
So this one didn't work.
Also I can not use the for loop as I have to think about the complexity O(n) for my method.
Already complexity has reached to O(n)2 (square).
**What I want is **
if sum of two numbers is target then I want to get the index of those numbers.
This can be done by converting the Stream<Integer> into a IntStream which has a toArray() method which generates an int[]
l1.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray()

Reverse Array (HackerRank) [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
Am I leaning in the right direction with my code? I'm currently working on hacker rank and am on the easy section of data structures yet I still am confused about how to reverse this array!
Out of all my attempts, I like these two that I did. Check it out.
one attempt:
two attempts:
You can reverse array in two ways
Either by fetching elements from last to start index and putting elements into new array
for example
int[] b = new int[n];
for(int i = n-1; i>=0 ; i--){
n[i] = arrayTobeReverse[i];
}
for more you can visit : https://www.geeksforgeeks.org/reverse-an-array-in-java/
By using Collection.reverse() method first you have to convert array into List using Arrays.asList(array) you can create List using array and then reverse the List.
for example :
import java.util.*;
public class ReverseDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List<String> mylist = new ArrayList<String>();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List : " + mylist);
// Here we are using reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}
You should be walking down the input array, then populating the target array in the opposite direction:
public static int[] reverseArray(int[] a) {
int[] b = new int[a.length];
for (int i=0; i < a.length; ++i) {
b[i] = a[a.length-i-1];
}
return b;
}
Just for fun, here is way to reverse the order of an original array, without using any extra storage:
// give input int[] a
for (int i=0; i < a.length / 2; ++i) {
a[i] = a[a.length-i-1];
}
Note that this approach just walks down half of the array, and swaps elements about the median.

Java Null Pointer with String Array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.

How to set size of two dimensional ArrayList?

So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.

How to check index of integer array element in java? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

Categories