I got this line of code when I asked the teacher for some help, but I get a redline below the last part. What could be wrong? The error message: "The type of the expression must be an array type but it resolved to ArrayList" I don't understand that, please help me to understand.
ArrayList<Point>[] touchPoints = new ArrayList<Point>()[2];
I want to have two lists to save Points. I guess I call each list like touchPoints[0]; and touchPoints[1]; !?
EDIT:
I guess I can keep it simple and just use two different List like this!?:
points1 = new ArrayList<Point>();
points2 = new ArrayList<Point>();
You have created an array of ArrayLists. This demo shows how they are used together
import java.util.ArrayList;
public class ArraysAndLists {
public static void main(String[] args) {
ArrayList<String>[] touchPoints = new ArrayList[2];
// Adding values
touchPoints[0] = new ArrayList<String>();
touchPoints[0].add("one string in the first ArrayList");
touchPoints[0].add("another string in the first ArrayList");
touchPoints[1] = new ArrayList<String>();
touchPoints[1].add("one string in the second ArrayList");
touchPoints[1].add("another string in the second ArrayList");
// touchPoints[2].add("This will give out of bounds, the array only holds two lists");
// Reading values
System.out.println(touchPoints[0].get(0)); // returns "one string in the first ArrayList"
System.out.println(touchPoints[1].get(1)); // returns "another string in the second ArrayList"
}
}
check out this Question
The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.
You are mixing two things:
Constructing a plain array
Constructing an ArrayList
Constructing an array
A plain array is very low level. Does not have methods, and its length is fixed after you create it.
MyType[] anArray = new MyType[10];
Constructing an ArrayList
ArrayList is just an implementation of a type of Collection
Collection<MyItemType> aCollection = new ArrayList<MyItemType>();
What to do in your case?
You want a plain array of collections (which implementation is ArrayList). So:
// Create the array, use the interface in case you need to change the implementation later on
Collection<Point>[] touchPoints = (Collection<Point>) new Collection[2];
// Create each collection within that array, using the ArrayList implementation
touchPoints[0] = new ArrayList<Point>();
touchPoints[1] = new ArrayList<Point>();
How to do it better?
Try to think about why you need a plain array:
if it's just 2 elements, and always fixed, simply create two member variables.
if number can vary, just create a Collection of Collections (Collection>)
Edit given your use case:
Just create a class to hold your user input:
class UserInput {
public UserInput() {
user1TouchPoints = new ArrayList<Point>();
user2TouchPoints = new ArrayList<Point>();
}
// Add accessors and all
private Collection<Point> user1TouchPoints;
private Collection<Point> user2TouchPoints;
}
If you plan to have more players, simply use a map
class UserInput {
public UserInput() {
usersTouchPoints = new HashMap<Integer, Collection<Point>>();
}
public Collection<Point> getUserTouchPoints(Integer userId) {
return usersTouchPoints.get(userId);
}
public void addUserTouchPoints(Integer userId, Collection<Point> input) {
Collection<Point> points = usersTouchPoints.get(userId);
if (points==null) {
points = new ArrayList<Point>();
userTouchPoints.put(userId, points);
}
points.addAll(input);
}
// Maps a user ID (or index) to its touch points
// If you are using Android, use SparseArray instead of Map, this is more efficient
private Map<Integer, Collection<Point>> usersTouchPoints;
}
Related
import java.util.*;
class Cube{
int width;
int height;
public Cube(int width, int height){
this.width = width;
this.height = height;
}
public String toString(){
String s = "[" + width + "," + height + "]";
return s;
}
}
class myClass {
public static void main(String[] args) {
LinkedList<Cube>[] myCubes;
myCubes = new LinkedList[3];
myCubes[0] = new LinkedList<Cube>();
myCubes[1] = new LinkedList<Cube>();
myCubes[2] = new LinkedList<Cube>();
myCubes[0].add(new Cube(5,2));
myCubes[0].add(new Cube(3,6));
myCubes[1].add(new Cube(3,3));
myCubes[1].add(new Cube(2,2));
myCubes[2].add(new Cube(1,2));
myCubes[2].add(new Cube(5,9));
}
}
I understand that I have an array of arrays. However, I can't quite figure out how to access a single value from a Cube instance in the array.
I would appreciate it if you could help show how to access a single field.
For example, how could I individually access the value 6
myCubes[0].add(new Cube(3,6));
I know that with single instances, you use the dot operator such as
myCubes.width;
myCubes.height;
However, I have no idea how to do access single fields from an array of array of instances.
I would truly appreciate your help.
Thank you
As the others showed you already in the comments.
I tried it out by myself.
If it would be an array of arrays you could simply use
myCubes[0][1].height
But as the LinkedList is not an Array but an Linked List you need to use the get method of linked list to get your element from the list.
System.out.print(myCubes[0].get(1).height);
LinkedList<Cube>[] myCubes ... I understand that I have an array of arrays
No, this not array of arrays, this is array of LinkedList. To
access list you need myCubes[index]
but to access elements from list you need *someList*.get(index).
If we combine those two we get something like myCubes[0].get(1) (just like you did with myCubes[0].add(new Cube(3,6)); where you needed to use add method on a list to put Cube in it).
But generally we should avoid generic types and arrays. Arrays would like to guarantee that they hold only valid values, so they are checking at runtime type of elements which are placed in it to see if they match type of array. For instance while this code will compile:
String[] strArray = new String[10];
Object[] objArr = strArray;
objArr[0] = new Integer(1);
we will get at runtime ArrayStoreException because we attempted to place Integer into array which was supposed to hold only Strings (even if we did it via Object[] reference, type of array is still String[] because that is what we decided on at new String[size]).
But problem with generics is that they are erased at runtime. Because of that it is possible to have code like
List<String> strList = new ArrayList<>();
Object o = strList;
List<Integer> intList = (List<Integer>) o;
intList.add(1);
System.out.println(strList);//this prints [1] !!!
So as you see generic types aren't really that safe (its safety exists mainly at compilation time) so arrays don't like them because they reduce their safety.
So instead of arrays you should use another List like List<List<Cube>>. This way compiler will not complain about mixing arrays and generic types (because there will be no more arrays - at least in our code). Your code using lists can look like:
List<List<Cube>> myCubes = new ArrayList<>();
myCubes.add(new LinkedList<>());
myCubes.add(new LinkedList<>());
myCubes.add(new LinkedList<>());
myCubes.get(0).add(new Cube(5,2));
myCubes.get(0).add(new Cube(3,6));
myCubes.get(1).add(new Cube(3,3));
myCubes.get(1).add(new Cube(2,2));
myCubes.get(2).add(new Cube(1,2));
myCubes.get(2).add(new Cube(5,9));
System.out.println(myCubes.get(0).get(1).width);
System.out.println(myCubes.get(0).get(1).height);
System.out.println(myCubes.get(0).get(1));
I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods
I am writing a program that will take input of polynomials. Needing to create a new ArrayList for each polynomial input, I am needing a way to name each list without knowing the amount of polynomial beforehand. If a file has 2 polynomials I will need to name 2 arrays, but if more polynomials I will need to name more arrays. Is there anyway to automatically name arrays or variables with the iteration of a loop. I cannot figure out how. Variable names such as : P1 , P2, P3 etc. as the number of Polynomials increases is what I am searching for. Each polynomial will be read in line by line. I have attached my code, Though it is nowhere near complete. I imagine I will need to move the PolyCalc creation into the while loop and create a new PolyCalc for each line of input. I am looking to add this feature to the while loop in the main method.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class PolyProcessor {
static int polyNum = 0;
public static void main(String[] args) throws FileNotFoundException{
File polyfile = new File("polyinput.txt");
Scanner read = new Scanner(polyfile);
while (read.hasNextLine()){
PolyCalc c = new PolyCalc();
String j = read.nextLine();
c.add(j.split(";"));
polyNum++;}
}
}
class PolyCalc{
static int polyCount = 0;
static ArrayList polynomials = new ArrayList();
static void add(String[] strings){
for(int i = 0; i<strings.length;i++){
polynomials.add(strings[i]);
polyCount++;}
}
static Object get(int i){
return polynomials.get(i);
}
}
Why not use a (Hash) Map where the key is the variable name?
Map polys = new HashMap();
int count=0;
For ...
string key = String.format("p%02d",count++);
polys.put(key, newPoly(...));
I'd have to look up the String.format but something like that.
The order needs to be preserved so just choose long enough zero padded keys that you can sort. And/or use a linkedHashMap which keeps the insertion order.
As Stephen's answer and you said that arraylist is mandatory you could still use ArrayList
ArrayList numbers = new ArrayList();
HashMap<String,ArrayList> myPolys = new HashMap<String,ArrayList>();
and to use the HashMap
myPolys.put(what do you want to call them or your so "called" variables , numbers);
First of all, you can't do this using variables. Java does not allow you to declare variables dynamically. It is not that kind of programming language ...
If it is mandatory that the polynomials are stored in an ArrayList then:
get the user to refer to the polynomials by number (i.e. position in the list) instead of by name, or
create a hashmap that maps from names to positions in the list, or
store the polynomials in BOTH an ArrayList<String> AND a HashMap<String, String>.
Actually, I think that you may have misinterpreted the requirements for your programming exercise. I suspect that you are asked to represent each individual polynomial as an ArrayList (or a custom class that has an ArrayList inside it). Representing a polynomial as a String doesn't allow you to do any operations on it ... without first parsing the String and turning it into another form.
As you absolutely need to use ArrayList class to store your polynomials you can use its add(int index, E Element) method as follows:
List polynomials= new ArrayList();
for(int k=0;k < counter;k++){
polynomials.add(k, new Poly(...));
}
You won't have P0, P1, ... but polynomials.get(0), polynomials.get(1), ...
Thanks to gmhk in this.
I need to wrap five classes: linkedlist, treeset, hashset, and two classes I created myself.
The wrapper and my two classes are all implementing the same interface.
this is the wrapper constructor:
private Collection <String> collection;
public CollectionFacadeSet(java.util.Collection<java.lang.String> collection){
this.collection = collection;
}
now, in another class I want to create a 5 cell array that each cell houses a different set.
This line is OK:
static CollectionFacadeSet[] setArray = new CollectionFacadeSet[5];
BUT, when I create a method that fills the cells:
private static void initializieArray(){
setArray[0] = CollectionFacadeSet(HashSet<String>);
}
it throws me an error:
Syntax error on token ">", Expression expected after this token
How to initiate each cell with a different set type?
The expression
setArray[0] = CollectionFacadeSet(HashSet<String>);
is invalid. You would need something like
setArray[0] = new CollectionFacadeSet(new HashSet<String>());
instead.
static CollectionFacadeSet[] setArray = new CollectionFacadeSet[5];
Array will store the objects of CollectionFacadeSet so use new
setArray[0] = new CollectionFacadeSet(new HashSet<String>());
I have a Arraylist: ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
from an Object that includes a String and an double (Name and points).
public class PlayerBean{private String name;private double points;}
However for one of my Spinners I want to show only the name (String) in my Arraylist.
How do I manage to delete(remove) the double(points)?
I tried this without any success any ideas?
I am using the swinger for android. any idea?
ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
List<String> namesOnly = filterNames(playerlist);
private List<String> filterNames(ArrayList<PlayerBean> playerlist12) {
List<String> names = new ArrayList<String>();
for(PlayerBean b : playerlist12)
{
names.add(b.getName());
}
return names;
}
Your list contains PlayerBean objects and you can't temporarily delete member variables from objects. Thus you can't remove points from the list.
You could either use a List<String> instead or provide a spinner model that only displays the name. I assume you're using Swing, don't you?
Rather than removing them, why don't you make a new array List of String type, and assign all the names into this list. So you don't have any points.