ArrrayList use for user defined Class - java

I'm facing a problem in ArrrayList. Please help.
A test program in which has two data type String and int,
when add item by add method it give me error;
if Integer is add The method add(int, Test) in the type ArrayList is not applicable for the arguments (int)
and if String is add it give
The method add(Test) in the type ArrayList is not applicable for the arguments (String)
public cl* Test {
String firstName;
int rollNum;
public static void main(String[] args) {//this ArrayList work fine
ArrayList<Integer> Num=new ArrayList<Integer>();
for (int i = 0; i <10; i++) {
Num.add(i);
}
for (int i = 0; i < Num.size(); i++) {
System.out.print(Num.get(i));
}//this ArrayList work fine
ArrayList<String> Num2=new ArrayList<String>();
Num2.add("ali");
Num2.add("2");
ArrayList<Test> Num1=new ArrayList<Test>();
Num1.add("Char"); // now it generate Error
}

ArrayList<Integer> a means -> Creating an ArrayList of Integer objects.
ArrayList<String> b means -> Creating an ArrayList of String objects.
Similarly,
ArrayList<Test> c means -> Creating an ArrayList of Test objects.
So, you need to create a Test object to add it to the c list as it demands a Test object.
Now,
/* If you have this parameterized constructor.
I suggest you to have it if you dont have. */
Test obj = new Test("Fname",10);
obj can be inserted now in the c object. This could be implemented using the add method of the
ArrayList class.
c.add(obj); //Adds the object 'obj' to the ArrayList 'c'
This won't give error.

In the last statement you have created an array list of type Test
ArrayList<Test> Num1=new ArrayList<Test>();
So insert Test objects into it
For eg:-
Test test = new Test();
test.setFirstName("ABC");
test.setRollNo(23);
ArrayList<Test> Num1 = new ArrayList<Test>();
Num1.add(test);

Related

creating arrays within ArrayList java

I'm trying to create two different types of Arrays within one ArrayList. Set up constructors accordingly (I think), but when it comes to instantiating them I get an error message "arr cannot be resolved". I'm slowly but surely going round the bend. How do I get the ArrayList to accept a simple array with doubles? (It also has to accept other types so it's not just a question of changing the ArrayList itself).Here's the code for the constructors & main ArrayList:
class NumList implements Num
{
private ArrayList<Num> n1;
public NumList( NumDouble[] doubleArray )
{
n1 = new ArrayList<Num>();
for( NumDouble d : doubleArray )
n1.add( d );
}
public NumList(NumFloat[] floatArray )
{
n1 = new ArrayList<Num>();
for( NumFloat d : floatArray )
n1.add( d );
}
// methods of Num interface
}
And my test class looks like this -
import java.util.ArrayList;
public class Demo extends NumList {
public Demo(NumDouble[] doubleArray) {
//suggested automatically to add super here
super(doubleArray);
double[] arr = {(1.1), (2.2), (3.3), (4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(arr);
}
public static void main (String [] args){
arr.sqrt();
System.out.println("The numbers sq are "+ arr [0]);
}
}
The NumList class has just three methods including sort. I have tried wildcards as well as
It's probably something really easy ... any help appreciated.
Your ArrayList holds object of type Num, but you are trying to insert plain ol' doubles into it
double[] arr = {(1.1), (2.2), (3.3), (4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(arr);
double does not inherit from Num and so cannot be placed in an ArrayList<Num>. Also, no ArrayList constructor takes an array as a parameter, you have to convert your array to a collection with Arrays.asList(array). You would have to do something like this
NumDouble[] arr = {new NumDouble(1.1), new NumDouble(2.2), new NumDouble(3.3), new NumDouble(4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(Arrays.asList(arr));

how to get value from 2d arraylist

i have arraylists named sub and main,
ArrayList main = new ArrayList();
ArrayList sub=new ArrayList();
i add value to sub and then add sub to main.
example;
sub.add(1);
sub.add(2);
main.add(sub);
now i want to get all values inside sub
so i used following one but .get(j) gives me the error get >> canot find symbol
for (int i=0;i<main.size();i++) {
System.out.println();
for (int j=0;j<sub().size();j++) {
System.out.print(main.get(i).get(j));//error line
}
}
how can i get all values inside subarray of main arraylist
When you declare a variable as
ArrayList main;
This list holds Objects. This means that main.get(i) will only return an Object, even if you add ArrayLists. That's why you get a compiler error: Object doesn't have a method named get().
To fix the problem, you need to use generics:
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub=new ArrayList<>();
Now get() will return a List<Integer> which has a get() method, so the compiler error will disappear.
Generics could be your friend here:
ArrayList<ArrayList<Object>> main = new ArrayList<ArrayList<Object>>(); // or new ArrayList<>(); in Java 7+
ArrayList<Object> sub = new ArrayList<Object>(); // or new ArrayList<>();
If you can't or don't want to use generics, the solution is to cast the expression main.get(i) to an ArrayList first:
System.out.println(((ArrayList) main.get(i)).get(j));
Go through the following code
public class ArrayListDemo {
public static void main(String[] args) {
List<List<Integer>> main = new ArrayList<>();
List<Integer> sub = new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
//If you want to get values in sub array list
for(int i = 0; i < 1; i++){
List<Integer> arr = main.get(i);
for(Integer val : arr) System.out.println(val + "");
}
//If you want to print all values
for(List<Integer> list : main){
for(Integer val : list) System.out.println(val + "");
}
}
}
In the above code, I had declared an ArrayList (main) to keep all Array which are having Integer values. Also i had declared an another ArrayList (sub) to keep all Integer values.
I had used ArrayList data structure because of length of the List will be changing the
run time.
Good Luck !!!

Why i am getting "Remove type arguments" error for "List<String> list1 = new ArrayList<String>();"

i am trying to implementing ArrayList using String array.
while implementing i am getting Remove type arguments error in my eclipse.
ArrayList.java
import java.util.List;
public class ArrayList {
public static void main(String [] a)
{
String [] things = {"eggs","chicken","milk","butter"};
List<String> list1 = new ArrayList<String>();
for(String s: things)
list1.add(s);
String [] morethings = {"chicken","milk"};
List<String> list2 = (List<String>) new ArrayList ();
for(String y: morethings)
list2.add(y);
for(int i=0; i<list1.size();i++)
{
System.out.printf("%s ", list1.get(i));
}
}
}
You've defined your own ArrayList which is not a generic class. To use java.util.ArrayList simply rename your class to something else other than one of Java's built-in classes
You have used the class java.awt.List which is used for GUI List options such as creating a drop-down list, and thus one cannot use collectibles/data structure, Iterators with such a list.
You need to use java.util.List for implementing:
List>= new LinkedList>();

A private data member changes (become empty) mysteriously somewhere

I have a public class named "InvertedIndex" which has two private data members:
private HashMap<String, ArrayList<Integer>> invertedList;
private ArrayList<String> documents;
I have generated getter and setter functions for them. I have a function named "buildFromTextFile" which fills both of the data members, and I have another function called "processQuery". I wrote a test unit in class "InvertedIndexTest" for processQuery which is as follows:
#Test
public void testProcessQuery() throws IOException{
InvertedIndex invertedIndex = new InvertedIndex();
String query = "ryerson award";
ArrayList<String> expectedResult = new ArrayList<String>();
expectedResult.add("ryerson award ??..23847");
invertedIndex.buildFromTextFile("input.tsv");
ArrayList<String> result = processQuery(query, 5);
Assert.assertEquals(expectedResult, result);
}
In this function, in debugging mode, when the function "buildFromTextFile" is called, the code will go to the class "InvertedIndex" and fill the data members, so at the end of this function the data members has correct data in them. When the running comes back to this unit test function again if I watch invertedIndex.getInvertedList().ToString(), I can see that the data is still correct. Then the function processQuery is called, and when the running goes to the "InvertedIndex" class, and inside this function, the invertedList().ToString() is empty. It seems that all the data is lost somewhere, but I don't know where. I would appreciate your help.
This is the processQuery method:
public ArrayList<String> processQuery(String query, int k){
ArrayList<String> result = new ArrayList<String>();
ArrayList<Integer> resultIds;
String[] queryWords = query.split("\\W+");
ArrayList<Integer> list1;
resultIds = invertedList.get(queryWords[0]);
for (int i = 1; i < queryWords.length; i++) {
list1 = invertedList.get(queryWords[i]);
resultIds = intersect(list1, resultIds);
}
Collections.sort(resultIds);
for (Integer item : resultIds) {
result.add(documents.get(item));
}
return result;
}
resultIds is null when this line runs:
resultIds = invertedList.get(queryWords[0]);
I put a breaking point at the very first line of queryProcess function, and both data members are empty.
More problems with your invertedList, I see. :-)
This is actually being caused by the exact same problem you had previously:
Hashmap get function returns null
Line
ArrayList<String> result = processQuery(query, 5);
Should read
ArrayList<String> result = invertedIndex.processQuery(query, 5);
Recommend moving all your tests to a completely separate file. That would save you these field reference headaches.

Bug: Null pointer deference of String

The test code below leads to a "null pointer deference" bug on a String Array(on line 6). This leads to a NullPointerException.
public class TestString {
public static void main (String args[]) {
String test [] = null;
for (int i =0; i < 5; i++) {
String testName = "sony" + i;
test [k] = testName;
}
}
}
-- How do I fix this?
-- What is it that causes this bug?
Thanks,
Sony
You need to initialize your array like this, before :
test = new String[5];
Whenever you use an array, the JVM need to know it exists and its size.
In java there are many way to initialize arrays.
test = new String[5];
Just create an array with five emplacements. (You can't add a sixth element)
test = new String[]{"1", "2"};
Create an array with two emplacements and which contains the values 1 and 2.
String[] test = {"1", "2"};
Create an array with two emplacements and which contains the values 1 and 2. But as you noticed it must be donne at the same time with array declaration.
In Java arrays are static, you specify a size when you create it, and you can't ever change it.
There are too many errors in your code.
1) What is k?
2) You need to initialize the test array first.
String test[] = new String[5]; // or any other number
You are not initializing your array. On the third row you set it to null and then on the sixth row you're trying to set a string to an array that does not exists. You can initialize the array like this:
String test [] = new String[5];
Change String test[] = null; to String test[] = new String[5];
an array must be initialized.
See: http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Categories