transfer arraylist to double array[0] in java - java

i have this code:
public class Test{
arrayList<String> list = new ArrayList<String>();
String[][] temp_list;
public static void main(String[] args)
{
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
i want to transfer the first item in 'list' into temp_list[0].compiling is success but i got error when i run it.this is the error:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:this line=>temp_list[0] = temp.split(" ");)
anyone can help me?

This is because you haven't allocated any 2D-array for temp_list. (Which array should the result of split be stored in?)
Here's a working version of your snippet.
import java.util.ArrayList;
public class Test {
static ArrayList<String> list = new ArrayList<String>();
static String[][] temp_list;
public static void main(String[] args) {
list.add("hello wold");
// allocate memory for 10 string-arrays.
temp_list = new String[10][]; <-----------
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}

This code would will not compile since list is declared as a member variable of the class but main is a static method.
As written, list has nothing added too so the call to list.get(0) will throw an Exception (not null pointer though).
The array temp_list is not allocated (no new) in the code given so trying assign into it will throw a null pointer exception.

You need to initialize temp_list before you use it. You need to specify the size of the array. For example:
int sizeOfArray = 5;
String[][] temp_list = new String[sizeOfArray][];

Related

Adding a array list to arraylist

import java.util.*;
class test2{
static void fun(int i,int arr[],List<Integer> l,int n,List<List<Integer>> res){
if(i==n){
if(l.size()!=0){
//System.out.println(l.size());
res.add((l));
//System.out.println(res);
}
//System.out.println(l);
return;
}
l.add(arr[i]);
fun(i+1,arr,l,n,res);
//System.out.println(l);
l.remove(l.size()-1);
//System.out.println(l);
fun(i+1,arr,l,n,res);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
List<Integer> l=new ArrayList<>();
List<List<Integer>> res=new ArrayList<>();
fun(0,arr,l,n,res);
System.out.println(res);
}
}
in fun function while i am adding a List to other List it is adding empty list i could find the reason can somebody help me this program is about finding the different combinations of given array
You can use res.add((new ArrayList<>(l)) instead of res.add((l)).
Why should use (new ArrayList<>(existing_list))?
When you update any primitive value then put in a list you can update again that primivite value. That does not change the value in list. But an object does not work like that. Well we can say it causes kind of pointer. When you update an object then it updates the values in its address. Let me show you a short example.
public class MyObject {
private List<String> list = new ArrayList<>();
public MyObject() {
list.add("added in Constructor");
}
public List getList() {
return list;
}
}
public static void main(String[] args) {
MyObject myObject = new MyObject();
System.out.println("--> Object list (Before added anything in main) : ");
myObject.getList().forEach(System.out::println);
List list = myObject.getList();
list.add("added in Main");
System.out.println("--> local list : ");
list.forEach(System.out::println);
System.out.println("--> Object list (After added a value in main) : ");
myObject.getList().forEach(System.out::println);
}
And the ouput is :
--> Object list (Before added anything in main) :
added in Constructor
--> local list :
added in Constructor
added in Main
--> Object list (After added a value in main) :
added in Constructor
added in Main
I did not set up a new Arraylist or create new one but my private list in MyObject is updated even if I just do changes in main function.
But instead of list If I returned new Array<>(list) then even if I update the list in main, my list would never change. Because I return another address with new Array<>(list). So you should add your list with another addres. I mean another Arraylist. So you can use res.add((new ArrayList<>(l)) instead of res.add((l)).

Why changes in sublist are reflected in the original list in Java... how to avoid this?

// "static void main" must be defined in a public class.
import java.util.*;
public class Main {
static void func(ArrayList<ArrayList<Integer>> arr) {
ArrayList<Integer> arr1 = new ArrayList();
arr1.add(0);
arr.add(arr1);
arr1.set(0,5);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
func(arr);
for(int i=0;i<arr.size();i++) {
for(int j=0;j<arr.get(i).size();j++) {
System.out.print(arr.get(i).get(j));
}
System.out.println();
}
}
}
In the above code, we add an 1D arraylist of 1 element (0) to the 2D arraylist arr, but when we change the value in the 1D arraylist from 0 to 5, why is the same change reflected in the 2d arraylist, and most importantly, how exactly do we avoid this?
By default, Java Lists are mutable and you can easily change their content by adding or removing elements. In addition to this, your arr List has a reference to arr1 and not a copy of it. This means that whenever you change 1D this change is also reflected in arr because both arr1 and the content of arr reference to the same exact List.
One way to avoid this is actually copying the arr1 List before adding it to arr as follows:
static void func(ArrayList<ArrayList<Integer>> arr) {
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(0);
arr.add(new ArrayList<>(arr1));
arr1.set(0,5);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
func(arr);
for(int i=0;i<arr.size();i++) {
for(int j=0;j<arr.get(i).size();j++) {
System.out.print(arr.get(i).get(j));
}
System.out.println();
}
}
Mind the changed line arr.add(new ArrayList<>(arr1));. This guarantees that the reference that arr holds is different than the reference of the original arr1. You are basically creating a new List.
Although this fixes your case, it might not work for every List because it depends on its content. This works on your case because Integer is an immutable class, but if you would have a List of a mutable class, then this wouldn't be enough because both Lists would reference exactly the same objects. An example of this is below:
public static void main(String[] args) {
ArrayList<ArrayList<MutableClass>> arr = new ArrayList<>();
ArrayList<MutableClass> arr1 = new ArrayList<>();
arr1.add(new MutableClass("original"));
arr.add(new ArrayList<>(arr1));
System.out.println(arr.get(0));
// now let's change the property of arr1 MutableClass to something else
arr1.get(0).setProperty("changed");
System.out.println(arr.get(0));
}
public static class MutableClass {
private String property;
public MutableClass(String property) {
this.property = property;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
#Override
public String toString() {
return "MutableClass{" +
"property='" + property + '\'' +
'}';
}
}
As you can see by running the code, changing the object in arr1, also changes the object in arr even if you create a new List. The only way to overcome this is by making MutableClass immutable or by deep copying the original arr1 List before adding it to arr. This means you would need to copy every single object inside arr1 as follows:
public static void main(String[] args) {
ArrayList<ArrayList<MutableClass>> arr = new ArrayList<>();
ArrayList<MutableClass> arr1 = new ArrayList<>();
arr1.add(new MutableClass("original"));
ArrayList<MutableClass> copiedList = new ArrayList<>();
for (MutableClass object : arr1) {
copiedList.add(new MutableClass(object));
}
arr.add(copiedList);
System.out.println(arr.get(0));
// now let's change the property of arr1 MutableClass to something else
arr1.get(0).setProperty("changed");
System.out.println(arr.get(0));
}
public static class MutableClass {
private String property;
public MutableClass(String property) {
this.property = property;
}
public MutableClass(MutableClass other) {
this.property = other.property;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
#Override
public String toString() {
return "MutableClass{" +
"property='" + property + '\'' +
'}';
}
}
To avoid 5 getting reflected in 2D list
create a new array list from arr1 in method func() and add it to arr(the 2D list) as shown below.
static void func(ArrayList<ArrayList<Integer>> arr) {
ArrayList<Integer> arr1 = new ArrayList();
arr1.add(0);
arr.add(new ArrayList<>(arr1));
arr1.set(0,5);
}
The reason for the behaviour:
Java is pass by value
When we do
func(arr);
in main method, the reference to the actual array list object in heap is passed as value to the method "func()".
Inside func, hence arr will be pointing to the same object.
When we add the array list newly created arr1 into arr, the reference to actual object corresponding to arr1 gets added to the actual 2D array.
This is because both arr of func() as well as arr of main() refers to same object in heap.
When we try to change something in arr1 list,
it is referenced by arr. So, it will be still visible to arr.
Printing the list in main gives output 5.
But when we create a new array list and add that to arr in func(), as below
arr.add(new ArrayList<>(arr1));
then the list got added to arr will be different from arr1.
Hence,
while printing in main(),
the 2D list holds the reference to newly created array list
(ie; new ArrayList<>(arr1)).
So, it will not get affected by changing to 5 by the line
arr1.set(0,5);
This will still give 0 while printing the list arr in main().

Display ArrayList of char in Java

I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}
First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.

Passing a string array as a parameter to a function java

I would like to pass a string array as a parameter to a function. Please look at the code below
String[] stringArray = {'a', 'b', 'c', 'd', 'e'};
functionFoo(stringArray);
Instead of:
functionFoo('a', 'b', 'c', 'd', 'e');
but if I do this I am getting an error stating that convert String[] into String. I would like to know if it is possible to pass the values like that or what is the correct way to do it.
How about:
public class test {
public static void someFunction(String[] strArray) {
// do something
}
public static void main(String[] args) {
String[] strArray = new String[]{"Foo","Bar","Baz"};
someFunction(strArray);
}
}
All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.
There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-
String concat (String ... strings)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < strings.length; i++)
sb.append (strings [i]);
return sb.toString ();
}
Here we can call the function like concat(a,b,c,d) or any number of params you want.
More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html
I believe this should be the way this is done...
public static void function(String [] array){
...
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
look at familiar main method which takes string array as param
More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}
Feel free to use this how ever you like.
/*
* The extendStrArray() method will takes a number "n" and
* a String Array "strArray" and will return a new array
* containing 'n' new positions. This new returned array
* can then be assigned to a new array, or the existing
* one to "extend" it, it contain the old value in the
* new array with the addition n empty positions.
*/
private String[] extendStrArray(int n, String[] strArray){
String[] old_str_array = strArray;
String[] new_str_array = new String[(old_str_array.length + n)];
for(int i = 0; i < old_str_array.length; i++ ){
new_str_array[i] = old_str_array[i];
}//end for loop
return new_str_array;
}//end extendStrArray()
Basically I would use it like this:
String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.
I think you forget to register the parameter as String[]
please check the below code for more details
package FirstTestNgPackage;
import java.util.ArrayList;
import java.util.Arrays;
public class testingclass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("Hello");
int size = 7;
String myArray[] = new String[size];
System.out.println("Enter elements of the array (Strings) :: ");
for(int i=0; i<size; i++)
{
myArray[i] = "testing"+i;
}
System.out.println(Arrays.toString(myArray));
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
System.out.println("Enter the element that is to be added:");
myArray = myList.toArray(myArray);
someFunction(myArray);
}
public static void someFunction(String[] strArray)
{
System.out.println("in function");
System.out.println("in function length"+strArray.length );
System.out.println(Arrays.toString(strArray));
}
}
just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...
Thank you

how can we access individual int value from LinkedHashset<set<Integer>? Through string is it possible

I want to remove duplicates e.g.{ {1,2,3}, {2,3,1},{3,2,1},{2,1,3} } are duplicates of {2,3,1} or any one from given 4 sets.for this i converted 2D Integer array into LinkedHashSet which removed duplicates but when i am converting back to array (due to need in algorithm) i am unable to access individual elements.is it possible? if not, what is the other way.if yes what is problem in the code.given below.please resolve.
my own other thinking: as i think through string is it possible?
e.g { {2,3,1},{-3,-2,-4},........... } insert in Set making ArrayList of each 3 element set e.g.{2,3,1},{-3,-2,-4},{3 element}, .....and then parseInt to access individual element as {2},{3},{1},{-3},{-2},{-4},... will it work?
import java.util.*;
class demo
{
Integer[][] orderedpair3k={{1,2,3},{1,3,-2},{2,3,-1},{1,2,3},{1,-3,-2},{2,-3,-1},{1,-2,-3},{1,3,2},{-2,3,-1},{1,-2,3},{1,-3,2},{-2,-3,-1}};
Set<Set<Integer>> r = new LinkedHashSet<Set<Integer>>();
Object[][] a;
public void init_clauses()
{
removeDuplicate();
System.out.println(r);
backToArray();
for(int i=0;i<a.length;i++)
System.out.println(a[0][i]);
}
public void removeDuplicate()
{
int i=orderedpair3k.length;
for(int j=0;j<i;j++)
r.add(new LinkedHashSet<Integer>(Arrays.asList(orderedpair3k[j])));
}
public void backToArray()
{
ArrayList<Set<Integer>> arr=new ArrayList<Set<Integer>>(r);
a = new Object[arr.size()][3];
for(int i=0;i<a.length;i++)
a[i]=arr.toArray(new Object[i]);
}
}
public class sat
{
public static void main(String[] arg){
demo S = new demo();
S.init_clauses();}
}
//in the above code i am unable to access individual element because in the array Set is inserted as Object even i tried using ((Integer)a[i][j]).intValue() i think this is due to Arrays.asList(orderedpair3k[j]) how this problem can be resolve?
Seems quite straightforward:
Integer[][] result = new Integer[r.size()][3];
int c = o;
for (Set<Integer> s : r)
result[c++] = s.toArray(new Integer[3]);

Categories

Resources