How to change Vector to Array or ArrayList? - java

I am trying to learn ArrayList and Vector.
If for example I have private Vector cardsInMyHand; can I change it to ArrayList. As you see or I am wrong.
private Vector numbers;
.
.
.
Vector studentNumbers;
studentNumbers = new Vector();
public int getNumbers(Vector studentNumbers, int x)
{
if (x >= 0 && x < studentNumber.size())
{
return ((Integer)hand.elementAt(x)).intValue();
} else
{
return 0;
}
}
change to private ??????; ...... ArrayList<String> studentNumbers = new ArrayList<String>();
Can I do this ?
public int getNumbers(ArrayList studentNumbers, int x)
{
if (x >= 0 && x < studentNumber.size())
{
return ((Integer)hand.elementAt(x)).intValue();
} else
{
return 0;
}
}

Yes, but your syntax has a few typos. And you should not use Raw Types. Finally, I suggest you use the List interface and read about Autoboxing and Unboxing.
public int getNumbers(List<Integer> studentNumbers, int x) {
if (x >= 0 && x < studentNumbers.size()) {
return studentNumbers.get(x);
} else {
return 0;
}
}

Check the below example with type safety.
public ArrayList<String> convertVectorToList(Vector<String> studentNoVec){
return new ArrayList<String>(studentNoVec);
}
public static void main(String[] args) {
Vector<String> v= new Vector<String>();
v.add("No1");
v.add("No2");
Test a = new Test();
for(String no : a.convertVectorToList(v)){
System.out.println(no);
}
}

First, Java Vector class considered obsolete or deprecated. If you want to convert Vector to an ArrayList use the below mentioned way. Simple and easy.
// convert vector to araryList
public ArrayList convertVectorToList(Vector studentNoVec){
return new ArrayList(studentNoVec);
}

Related

We can't add a primitive type value to a ArrayList<Integer> right?? Why is this code working ?? (arrayList should only contain only objects right? )

We can't add a primitive type value to a ArrayList right?? Why is this code working ?? (arrayList should only contain only objects right? )
static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) {
int aPoints = 0;
int bPoints =0;
for(int i=0;i<a.size();i++){
if(a.get(i)>b.get(i)){
aPoints++;
} else {
if(a.get(i)<b.get(i)) {
bPoints++;
} else {
if(a.get(i)==b.get(i)){
aPoints = aPoints + 0;
bPoints = bPoints + 0;
}
}
}
}
ArrayList<Integer>points = new ArrayList<>();
points.add(aPoints);
points.add(bPoints);
return points;
}

Problems understanding constructors like the one in ArrayList.class

While coding I was trying to declare a class that can create an arraylist of arraylists, but soon enough I found it hard to define a proper constructor for my class. I wanted to define some methods for me to handle the huge outer arraylist(1000*1000), but I might be affected by C and always tried to use something like structdef.
How should I define my class? I guess declaring every lines seperatedly is not a wise choice, and I don't want to use 2D arraylist directly. Besides, how should I define a constructor to get an object that is an 2D arraylist?
//Update here
Below is my code example:
class farbicMap {
//attribute
ArrayList<Integer> farbicUnit = new ArrayList<Integer>();
//constructor
farbicMap () {
for (int i=0;i<1000;++i) {
farbicUnit.add(0);
}//this gives an arraylist with size of 100
//I want to use the above arraylist to construct another list here
}
//method
setUnitValue(int v) {
...
}
}
Seems that I didn't really understand the concept of class... I wanted to use the class to represent a map with some nodes. Now that's much clearer to me.
This is how I understood your consern:
class Test {
public static void main(String[] args) {
Board board = new Board(1000, 1000);
board.put(1, 2, "X");
Object x = board.get(1, 2);
System.out.println("x = " + x);
}
}
class Board {
private final int xSize;
private final int ySize;
private ArrayList<ArrayList<Object>> board = new ArrayList<>();
public Board(int xSize, int ySize) {
this.xSize = xSize;
this.ySize = ySize;
for (int i = 0; i < xSize; i++) {
board.add(getListOfNulls());
}
}
public Object get(int x, int y) {
return board.get(x).get(y);
}
public void put(int x, int y, Object toAdd) {
List<Object> xs = board.get(x);
if (xs == null) {
xs = getListOfNulls();
}
xs.add(y, toAdd);
}
private ArrayList<Object> getListOfNulls() {
ArrayList<Object> ys = new ArrayList<>();
for (int j = 0; j < ySize; j++) {
ys.add(null);
}
return ys;
}
}
You should use Array if size is fixed.

Writing an equals method to compare two arrays

I have the following code, I believe something is off in my equals method but I can't figure out what's wrong.
public class Test {
private double[] info;
public Test(double[] a){
double[] constructor = new double[a.length];
for (int i = 0; i < a.length; i++){
constructor[i] = a[i];
}
info = constructor;
}
public double[] getInfo(){
double[] newInfo = new double[info.length];
for(int i = 0; i < info.length; i++){
newInfo[i] = info[i];
}
return newInfo;
}
public double[] setInfo(double[] a){
double[] setInfo = new double[a.length];
for(int i = 0; i < a.length; i++){
setInfo[i] = a[i];
}
return info;
}
public boolean equals(Test x){
return (this.info == x.info);
}
}
and in my tester class I have the following code:
public class Tester {
public static void main(String[] args) {
double[] info = {5.0, 16.3, 3.5 ,79.8}
Test test1 = new Test();
test 1 = new Test(info);
Test test2 = new Test(test1.getInfo());
System.out.print("Tests 1 and 2 are equal: " + test1.equals(test2));
}
}
the rest of my methods seem to function correctly, but when I use my equals method and print the boolean, the console prints out false when it should print true.
You are just comparing memory references to the arrays. You should compare the contents of the arrays instead.
Do this by first comparing the length of each array, then if they match, the entire contents of the array one item at a time.
Here's one way of doing it (written without using helper/utility functions, so you understand what's going on):
public boolean equals(Test x) {
// check if the parameter is null
if (x == null) {
return false;
}
// check if the lengths are the same
if (this.info.length != x.info.length) {
return false;
}
// check the elements in the arrays
for (int index = 0; index < this.info.length; index++) {
if (this.info[index] != x.info[index]) {
return false;
} Aominè
}
// if we get here, then the arrays are the same size and contain the same elements
return true;
}
As #Aominè commented above, you could use a helper/utility function such as (but still need the null check):
public boolean equals(Test x) {
if (x == null) {
return false;
}
return Arrays.equals(this.info, x.info);
}

Generic method returning ArrayList

I am trying to make a program that creates an ArrayList given the type as well as the values that will be put into the ArrayList. The input structure that we have to work with is "I 6 7 5 3 1 -1 2" with the I being the type Integer (or S for String, etc) and the first number (6) being how many values are in the ArrayList. I'm not sure how to instantiate the ArrayList.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String type = scan.next();
int length = scan.nextInt();
int counter = 0;
if (type.equals("I")) {
ArrayList<Integer> A = new ArrayList<Integer>;
}
else if (type.equals("S")) {
ArrayList<String> A = new ArrayList<String>;
}
else if (type.equals("D")) {
ArrayList<Double> A = new ArrayList<Double>;
}
else {
System.out.println("Invalid type");
}
while (scan.hasNext() && counter<length) {
String s1 = scan.next();
A.add(s1);
counter += 1;
}
System.out.print(A);
}
//Removes any duplicate values in the arraylist by checking each value after it
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
ArrayList<E> inArray = list;
for (int i = 0; i<inArray.size(); i++) {
for (int j = i+1; j<inArray.size(); j++) {
if (inArray.get(i) == inArray.get(j)) {
inArray.remove(j);
}
}
}
return inArray;
}
//Shuffles the contents of the array
public static <E> void shuffle(ArrayList<E> list) {
E temp;
int index;
Random random = new Random();
for (int i = list.size()-1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = list.get(index);
list.set(index, list.get(i));
list.set(i, temp);
}
System.out.print(list);
return;
}
//Returns the largest element in the given arraylist
public static <E extends Comparable<E>> E max(ArrayList<E> list) {
E max = Collections.max(list);
System.out.println(max);
return max;
}
I cannot in good conscious give you the answer you want, but rather I'll give you the answer you need.
DON'T DO THAT!
It serves no purpose at all. Datatype erasure at compile time of generics makes the ArrayList<Whatever> act equivalently to ArrayList<?> You cannot ascertain the generic type during runtime unless you type check the elements within the ArrayList
You might as well write this code, it'll give you the same exact results:
public static ArrayList<?> returnProper(String type) {
if(type.length() == 1 && "ISD".contains(type)) {
return new ArrayList();
} else {
System.out.println("Invalid type");
return null;
}
}
THUS, PLEASE DON'T DO THAT
Replace the second E with an "?" and then fix the method to return.
public static <T> ArrayList<?> returnProper(String type) {
if (type.equals("I")) {
return new ArrayList<Integer>();
} else if (type.equals("S")) {
return new ArrayList<String>();
} else if (type.equals("D")) {
return new ArrayList<Double>();
} else {
System.out.println("Invalid type");
}
return null;
}

Recursive with void method?

I have a problem with one of my program (my programming language is java) :
I have an object Douglas-Peucker which is an array of Points and I have an algorithm, the Douglas-Peucker algorithm. I want to work directly on this array of Points and here the problem begin. This is Douglas-Peucker algorithm :
protected Point[] coinImage;
// My constructor
public Peucker(Point [] tab) {
coinImage = new Point[tab.length];
for(int i = 0; i < coinImage.length; i++) {
coinImage[i] = new Point(tab[i].x, tab[i].y);
}
}
public Point[] algoDouglasPeucker() {
return douglasPeuckerAux(0,coinImage.length - 1);
}
public Point[] douglasPeuckerAux(int startIndex, int endIndex) {
double dmax = 0;
int index = 0;
for(int i = startIndex + 1; i < endIndex; i++) {
double distance = this.distancePointSegment(this.coinImage[i], this.coinImage[startIndex], this.coinImage[endIndex]);
if(distance > dmax) {
index = i;
dmax = distance;
}
} ***
if(dmax >= this.epsilon) {
Point[] recResult1 = douglasPeuckerAux(startIndex,index);
Point[] recResult2 = douglasPeuckerAux(index,endIndex);
Point [] result = this.unionTabPoint(recResult1, recResult2);
return result;
}
else {
return new Point[] { coinImage[0],coinImage[endIndex] };
}
}
*** my problem is here : both methods have a specific type of return : array of Point or I want to change this because I want to work directly on my attribut (coinImage).
How change this in void methods ?
Help me please !
Sorry I forget one method : I also want to change the type of this method :
public Point[] unionTabPoint(Point [] P1,Point [] P2) {
Point[] res = new Point[P1.length + P2.length];
for(int i = 0; i < P1.length;i++) {
res[i] = new Point(P1[i].x,P1[i].y);
}
int k = 0;
for(int j = P1.length; j < res.length; j++) {
res[j] = new Point(P2[k].x,P2[k].y);
k++;
}
return res;
}
She return the union of two array but without specific order.
Well the basic layout for a void recursive method is like this:
int i = 0;
public void recursive(){
if(i == 6){
return;
}
i++;
recursive();
}
You can keep looping the method, as it would return the the next line, of the method that called it. In this case, the return, would reach the '}' and terminate the method, as it is finished.
Hope I helped :D
Java is doing call by reference. It is possible to use an local instance of your result and/or use it in your parameterlist, for example method(x, y, Point[]) and force the method as a result, what is your method call. Like:
public void doSome(x,y) { x==0 ? return : doSome(x-1, y-1); }
I hope this is what you looking for ...(if not pls clarify more)
public void douglasPeuckerAux(int startIndex, int endIndex) {
...
Point[] newCoinImage = new Point[] { coinImage[0],coinImage[endIndex] };
coinImage = newCoinImage;
}
public void unionTabPoint(Point [] P1,Point [] P2) {
...
coinImage = res;
}

Categories