Convert ArrayList to Array - java

I'm having a little trouble converting an array list to an array in java.
I have a class called Table which contains an array list called applicants which takes Strings. When I use my toArray() function it doesn't seem to convert the array list into an array.
I know this because when i run the listArray() function it gives the error:
java.lang.NullPointerException.
Here is the code. Any help would be greatly appreciated.
public class Table {
public ArrayList<String> applicants;
public String appArray[];
public Table() {
applicants = new ArrayList<String>();
}
public void addApplicant(String app) {
applicants.add(app);
}
public void toArray() {
int x = applicants.size();
String[] appArray = new String[x];
appArray = applicants.toArray(appArray);
}
public void list() {
for (int i = 0; i < applicants.size(); i++) {
System.out.println(applicants.get(i));
}
}
public void listArray() {
for (int i = appArray.length; i > 0; i--) {
System.out.println(appArray[i]);
}
}
}

This is because you are shadowing the appArray field in your method here:
int x = applicants.size();
String[] appArray = new String[x];
appArray = applicants.toArray(appArray);
You create a new local variable called appArray when you should be using the appArray field you already have declared in your class.
You should do
public void toArray()
{
appArray = applicants.toArray(new String[0]);
}

appArray = new String[applicants.size()];
int index = 0;
for(String app:applicants){
appArray [index] = app;
index++;
}

Because both your ArrayList and Array should only have strings you can do this.
appArray = applicants.toArray(new String[0]);
More information in the javadoc.

Related

How can I make the Array List be called in another class java

I need to write a code that checks all the words in an array list and tells me how many of these have a certain length. I understand how to do that, but I can't figure out how to make the ArrayList to be read in the second class so I can apply it in the program.
MAIN
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
java.util.ArrayList myList = new java.util.ArrayList();
myList.add("cat");
myList.add("mouse");
myList.add("frog");
myList.add("dog");
myList.add("dog");
int len = in.nextInt();
WordList wl = new WordList();
wl.numWordsOfLength(len);
}
}
SECOND CLASS
public class WordList{
public int numWordsOfLength(int len){
int count = 0;
for(int i=0;i<len;i++){
if(((String)myList.get(i)).length()==len){
count++;
}
}
return count;
}
}
You need to pass the list as parameter:
public int numWordsOfLength(int len, List<String> myList){
int count = 0;
for(int i=0;i<myList.size;i++){
if((myList.get(i)).length()==len){
count++;
}
}
return count;
}
or via the WordList Constructor:
import java.util.List;
public class WordList{
private final List<String> myList;
WordList(List<String> myList){
this.myList = myList;
}
public int numWordsOfLength(int len){
int count = 0;
for (String s : myList) {
if (s.length() == len) {
count++;
}
}
return count;
}
}
Side node instead of :
java.util.ArrayList myList = new java.util.ArrayList();
just do :
import java.util.List;
....
List<String> myList = new ArrayList();
Full Running example:
public class Test {
public static class WordList{
private final List<String> myList;
WordList(List<String> myList){
this.myList = myList;
}
public int numWordsOfLength(int len){
int count = 0;
for (String s : myList) {
if (s.length() == len) {
count++;
}
}
return count;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<String> myList = new ArrayList<>();
myList.add("cat");
myList.add("mouse");
myList.add("frog");
myList.add("dog");
myList.add("dog");
int len = in.nextInt();
WordList wl = new WordList(myList);
System.out.println(wl.numWordsOfLength(len));
}
}
This depends on your interpretation of "read in the second class".
My guess is you want the second class to have "myList" as a private variable, so the code will work when you call the numWordsOfLength() function.
In order to do this, you should pass the array you built to WordList as a dependency. There are generally two ways to give an object a dependency. Either when you create the object (constructor based) or later by calling a method (setters).
So in main, your goal would be to do either:
WordList wl = new WordList();
wl.setList(myList)
wl.numWordsOfLength(len);
Or:
WordList wl = new WordList(myList);
wl.numWordsOfLength(len);
Either way, you will have to add "myList" variable inside the WordList and then expose it either via a separate setter method (setList) or in the constructor itself.
I'd prefer a constructor in this case, since the name of the class "WordList" implies that it IS a list of things and therefore should encapsulate the thing it is.
i.e.
public class WordList{
private List<String> myList;
public WordList(List<String> listOfWords) {
this.myList = listOfWords;
}
public int numWordsOfLength....
}
You don't need that second class at all, if you use Java 8+:
...
java.util.ArrayList<String> myList = new java.util.ArrayList();
myList.add("cat");
myList.add("mouse");
myList.add("frog");
myList.add("dog");
myList.add("dog");
int len = in.nextInt();
int count = myList.stream().map(String::length).filter(c->c==len).count(); <--that's your answer
...
If you prefer to use that second class, you can just use this "count" expression in your numWordsOfLength method in the WordList class once you've passed the list there as the previous answers suggest.
BTW, the loop in your WordList class seem to be incorrect: you're only iterating the list up to len, instead you want to iterate over the entire list. I assume the len variable is the searched lengths of a word:
public int numWordsOfLength(int len, List<String> list){
int count = 0;
for(int i=0;i<list.size();i++){
if(list.get(i).length()==len){
count++;
}
}
return count;
}

How to retrieve element from ArrayList containing long array

How to retrieve element from ArrayList<long[]>?
I wrote like this:
ArrayList<long []> dp=new ArrayList<>();
//m is no of rows in Arraylist
for(int i=0;i<m;i++){
dp.add(new long[n]); //n is length of each long array
//so I created array of m row n column
}
Now how to get each element?
every element in that list is an array... so you need to carefully add those by:
using anonymous arrays new long[] { 1L, 2L, 3L }
or especifying the size using the new keyword new long[5]
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}
You get the arrays the same way you get anything from an ArrayList. For example, to get the tenth long[] stored in the ArrayList, you'd use the get method:
long[] tenthArray = dp.get(9);
You could also have an ArrayList of objetcs that contain an array of longs inside. But the problem so far with your code is that you are not putting any values in each long array.
public class NewClass {
private static class MyObject {
private long []v;
public MyObject(int n) {
v = new long[n];
}
#Override
public String toString() {
String x = "";
for (int i = 0; i < v.length; i++) {
x += v[i] + " ";
}
return x;
}
}
public static void main(String[] args) {
ArrayList<MyObject> dp = new ArrayList();
int m = 3;
int n = 5;
for (int i = 0; i < m; i++) {
dp.add(new MyObject(n));
}
for (MyObject ls : dp) {
System.out.println(ls);
}
}
}

data provider with arraylist of array in Test NG

I have to send a array list of arrays to the test case using the dataprovider annotation. I have the below code but it is giving illegal argument exception. My arraylist size is 4096. Do I need to give such many arguments in test method.
#Test(dataProvider="combination_list")
public void checkbox_combination(List<int[]> obj) {
/*for(int i=0;i<=4095;i++) {
}*/
}
#DataProvider(name="combination_list")
public static Object[][] get_Combination_list() {
List<int[]> combinations_with_int_array = new ArrayList<int[]>();
int size_combination;
for(int i=0;i<=4095;i++) {
String checkbox_combination =Combination_List.intToString(i,12);
int[] single_combination = new int[12];
for (int j=0;j<=11;j++) {
if(j<11)
{
single_combination[j]=Integer.parseInt(checkbox_combination.substring(j, j+1));
}
else
{
single_combination[j]=Integer.parseInt(checkbox_combination.substring(j));
}
}
combinations_with_int_array.add(single_combination);
}
size_combination=combinations_with_int_array.size();
System.out.println("No of combinations : "+size_combination);
Object objArray[][] = new Object[size_combination][];
for(int i=0;i<size_combination;i++){
objArray[i] = new Object[1];
objArray[i][0] = combinations_with_int_array.get(i);
}
return objArray;
}
combinations_with_int_array is an arrayList of int[].
objArray[i][0] = combinations_with_int_array.get(i);
When you do a get on the list, it give you int[] which is the type of the argument, which it is adding to the Object[][]. So your test method should have the same argument.

The infamous object bug

I discovered what i think is a bug whilst using netbeans. When i call up my method to sort an array containing names(ob.sort) in alphabetical order it automatically sorts another array which contains the original names when it isn't supposed to as the original names is not assigned to anything after it has been populated with input at the beginning(ob.input).
I experienced this problem whilst writing larger programs(encountered more than once), but i made a simpler one to demonstrate this problem. It looks like much as i copied the class methods an pasted it below the main class making it easier for you to trace the variables in the program.
public static void main(String args[]){
ObjectTest ob = new ObjectTest();
ob.input();
String x[] = ob.getNames();
System.out.println(x[0]);
ob = new ObjectTest(x);
System.out.println(x[0]);
ob.sort();
System.out.println(x[0]);
String y[] = ob.getNamesrt();
System.out.println(x[0]);
}
}
/*import java.io.*;
import javax.swing.*;
public class ObjectTest {
String name[];
String namesrt[];
public ObjectTest(){
name = new String[3];
namesrt = new String[3];
}
public ObjectTest(String j[]){
namesrt = j;
}
public void input(){
for(int i = 0; i < name.length; i++){
name[i] = JOptionPane.showInputDialog("Enter name");
}
}
public void sort(){
if(!(namesrt == null)){
for(int i = 0; i < namesrt.length; i++){
for(int c = i + 1; c < namesrt.length; c++){
if(namesrt[i].compareToIgnoreCase(namesrt[c]) > 0){
String n = namesrt[i];
namesrt[i] = namesrt[c];
namesrt[c] = n;
}
}
}
}
else{JOptionPane.showMessageDialog(null,"Names not received");}
}
public String[] getNames(){
return name;
}
public String[] getNamesrt(){
return namesrt;
}
public void setNames(String j[]){
name = j;
}
public void setNamesrt(String j[]){
namesrt = j;
}
}*/
I discovered what i think is a bug whilst using netbeans.
Well, it may be a bug in your code. It's not a bug in Java or in Netbeans. It's just demonstrating the fact that arrays are reference types in Java, and the way that objects work.
Here's a short but complete program demonstrating the same effect:
public class Test {
public static void main(String[] args) {
String[] x = { "hello" };
// Copy the *reference*
String[] y = x;
System.out.println(y[0]); // Prints "hello"
x[0] = "new value";
System.out.println(y[0]); // Prints "new value"
}
}
The values of x and y here are references to the same array object... so if the array is changed "through" x, that change is still visible as y[0].
If you want to make your code create independent objects, you'll want to change this:
public ObjectTest(String j[]){
namesrt = j;
}
to:
public ObjectTest(String j[]){
namesrt = j.clone();
}
(Ideally change it to declare the parameter as String[] j, or better yet fix all your variable names to be more meaningful, but that's a different matter.)

Adding Multiple Values in ArrayList at a single index

I have a double ArrayList in java like this.
List<double[]> values = new ArrayList<double[]>(2);
Now what I want to do is to add 5 values in zero index of list and 5 values in index one through looping.
The zeroth index would have values {100,100,100,100,100}
The index 1 would have values {50,35,25,45,65}
and all of these values are stored in a double array in following order
double[] values = {100,50,100,35,100,25,100,45,100,65}
How can i do it?
#Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit:
If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this:
(I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
How about
First adding your desired result as arraylist and
and convert to double array as you want.
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList inside the arrObjList. I hope this will help you.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.

Categories