How to put array in an object in Java? - java

I am trying to clone an array and return as an object, not an array type.
z
public IntVector clone()
{
IntVector cloneVector = new IntVector(3);
int[] newItems = new int[10];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
cloneVector = newItems; // is there a way to do something like this??
return cloneVector;
}
Main method looks like this
public static void main(String[] args)
{
IntVector vector = new IntVector(5);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
}
*there are two other methods which makes an array:IntVector() and puts value into array:push()

Declare a new constructor for IntVector which takes an int array and a count:
IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
Then you can write clone like this:
public IntVector clone() {
return new IntVector(items_, itemCount_);
}
You can make that new constructor private if you like, so only clone can use it.

Related

How to clone array in java with this code

This code generates unsorted array. My question is how do I clone the generated array so I can reuse the unsorted array in different sorting algorithms.
public class UnsortedData{
private int [] coreData;
private int maxArraySize;
private int currentArraySize;
public UnsortedData(int size){
this.maxArraySize = size;
this.coreData = new int[this.maxArraySize];
this.currentArraySize = 0;
}
public boolean addData(int data){
if (currentArraySize < maxArraySize)
{
coreData[currentArraySize] = data;
currentArraySize++;
return true;
}
return false;
}
public class dataSorting {
public static void main(String[] args) {
Random rand = new Random();
UnsortedData uD = new UnsortedData(1000000);
for (int x = 0; x < 50; x++) {
uD.addData(rand.nextInt(3000000));
}
}
Use build in methods from java.lang.Object to clone the original array and java.util.Arrays to sort the cloned array.
int[] arr = {6,9,4,5}; // original array
int[] arrCopy = arr.clone() // we created a copy of the array
Arrays.sort(arrCopy); // it sort the array that we cloned
References: Arrays Class , Class Object
Easiest way? Object.clone()
int[] arr = coreData.clone();
You can also use the Stream API or external libraries such as Apache Commons.

Casting from ArrayList<Object> to my own class

I have two ArrayLists, teamList1 and teamList2, which each contain five Team objects. I'm comparing those contents to each other in one of my methods. I must pass in these two ArrayLists as a single 2-element simple array argument, Objects[], into the method. I'm getting a compiler error because I'm struggling with casting from type Objects into type Team. In other words, changing from a Collection to a simple array back to a Collection is giving me an error. Anyone have a tip on my casting error?
CommonElements.java
package test;
import javax.swing.*;
import java.util.*;
public class CommonElements {
List<Comparable> teamList1 = new ArrayList<Comparable>();
List<Comparable> teamList2 = new ArrayList<Comparable>();
List<Comparable> commonList = new ArrayList<Comparable>();
Object[] listCollection = new Object[2];
int comparisonCount;
public static void main(String[] args) {
new CommonElements();
}
public CommonElements() {
comparisonCount = 0;
Team a = new Team("Boston");
Team b = new Team("Seattle");
Team c = new Team("Newark");
Team d = new Team("Houston");
Team e = new Team("Salt Lske City");
teamList1.add(a);
teamList1.add(b);
teamList1.add(c);
teamList1.add(d);
teamList1.add(e);
Team f = new Team("Seattle");
Team g = new Team("Nashville");
Team h = new Team("St. Louis");
Team i = new Team("New York");
Team j = new Team("Boston");
teamList2.add(f);
teamList2.add(g);
teamList2.add(h);
teamList2.add(i);
teamList2.add(j);
listCollection[0] = teamList1;
listCollection[1] = teamList2;
findCommonElements(listCollection);
System.out.println(comparisonCount);
}
public Comparable[] findCommonElements(Object[] collections)
{
ArrayList<Object> objectTeam1 = new ArrayList<Object>(Arrays.asList(collections[0]));
ArrayList<Object> objectTeam2 = new ArrayList<Object>(Arrays.asList(collections[1]));
ArrayList<Team> team1 = (ArrayList)objectTeam1;
ArrayList<Team> team2 = (ArrayList)objectTeam2;
Team[] commonList = new Team[5];
int i = 0;
for(Team x:team1)
{
for(Team y:team2)
{
comparisonCount++;
if(x.compareTo(y) == 0)
{
commonList[i] = x;
System.out.println(commonList[i].teamName);
i++;
break; /*to ensure it looks for only one match per entry*/
}
}
}
return commonList;
}
public int getComparisons()
{
return comparisonCount;
}
}
Team.java
package test;
public class Team implements Comparable<Team> {
String teamName = new String();
public void setName ( String n ) {
teamName = n;
}
public Team(String n) {
setName(n);
}
public int compareTo(Team x)
{
if(this.teamName.equals(x.teamName))
{
return 0;
}
else
{
return -1;
}
}
}
That is a very unfortunate and odd way of passing the arguments, but anyway, to make it work, you can do:
#SuppressWarnings("unchecked")
ArrayList<Team> team1 = (ArrayList<Team>)collections[0];
#SuppressWarnings("unchecked")
ArrayList<Team> team2 = (ArrayList<Team>)collections[1];
Your existing code was taking each ArrayList, putting it into a one element array, wrapping that array as a list, creating an ArrayList from it, and trying to view the ArrayList<ArrayList<Team>> as an ArrayList<Team>.
A few other things I see... you don't need to assign these to variables if you're only using them to add to the list:
Team a = new Team("Boston");
...
teamList1.add(a);
You can simply do:
teamList1.add(new Team("Boston"));
You don't need to create the listCollection array separately, because you can create it inline when passing the arguments:
findCommonElements(new Object[] { teamList1, teamList2 });
In your Team class, this:
String teamName = new String();
Should simply be:
String teamName;
In your compareTo method:
public int compareTo(Team x)
{
if(this.teamName.equals(x.teamName))
{
return 0;
}
else
{
return -1;
}
}
That should be:
public int compareTo(Team x)
{
return teamName.compareTo(x.teamName);
}
which is shorter, and honors the compareTo requirement that sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.

Java - Change values of an array by a method in a Class

Here is my code:
class Myclass {
private static int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
int[] array = new int[10];
}
}
It throws a java.lang.nullPointerException when trying to do this:
m.array[i] = i;
Can anybody help me please?
You have declared a local variable array in your constructor, so you're not actually initializing the array declared in Myclass.
You'll want to refer directly to array in the constructor. Instead of
int[] array = new int[10];
Use this
array = new int[10];
Additionally, you've declared array static in the scope of your Myclass class.
private static int[] array;
You only have one instance of Myclass here, so it doesn't matter, but normally this would not be static, if you're initializing it in a constructor. You should remove static:
private int[] array;
In your constructor you are making your assignment to a local variable names array, not the static class variable also named array. This is a scope problem.
I'm also guessing that since you access array via m.array, you want a member variable and not a static one. Here's the fix
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
rray = new int[10];
}
}
in MyClass() type this
this.array = new int [10];
instead of this
int[] array = new int[10];
Your code should be as below. In the constructor, instead of initializing the instance variable you created a new local variable and the instance variable was left uninitalized which caused the NullPointerException. Also the instance variable shouldn't be static.
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
array = new int[10];
}
}
First, if you plan to use array as a field of m (i.e. m.array) don't declare it as static, but:
private int[] array;
Next thing you have to do is to initialize it. Best place to do that is in the constructor:
public MyClass() {
array= new int[10]; //just array = new int[10]; don't put int[] in front of the array, because the variable already exists as a field.
}
The rest of the code should work.

final 2D array in Java

If I initialize an array in a Java method like:
final double[][] myArray = new double[r][c];
Will I be allowed to do this later in the method?
myArray[0] = new double[c];
Yes you can. For more on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I'll provide you an example of this:
public class Main {
public static void main(String[] args) {
final int[] finalArray = new int[5];
finalArray[0] = 10;
System.out.println(finalArray[0]);
finalArray[0] = 9001;
System.out.println(finalArray[0]);
finalArray = new int[5] //compile error!!!
}
}
This is because the final modifier will say that the reference to the array (the pointer) can't change, but the elements of the array (that could have another pointer) can change with no problem.
EDIT:
Another example with 2d array:
public class Main {
public static void main(String[] args) {
final int[][] array2d = new int[5][];
for(int i = 0; i < array2d.length;i++) {
array2d[i] = new int[6];
}
//the size of the rows can change with no problem.
array2d[0] = new int[8];
}
}

java: newbie on indexing object arrays

I wish to create a java method that returns an array of type: ABCout, where class ABCout is defined as:
public class ABCout {
public int numOut;
public double[] myArray;
}
and the java method is:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}
but I'm getting the error: java.lang.NullPointerException : null
Anyone see what I'm doing wrong?
You initialized the array, but not the objects in it. You probably need to do:
ABCout[] userABC = new ABCout[3];
for (int i = 0; i < userABC.length; ++i) {
userABC[i] = new ABCout();
}
Also, you need to instantiate myArray:
public class ABCout {
public int numOut;
public double[] myArray;
public ABCout() {
myArray = new double[10];
}
}
You need to instantiate the ABCout object you store in the array.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout(); // instantiate
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
/* here I only fill the 0'th element, but once working I will fill the others */
return userABC;
}
You're declaring an array of ABCout, but you're trying to access the first element of that array before assigning it.
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
userABC[0] = new ABCout();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
return userABC;
}
//add this
userABC[0] = new ABCount();
userABC[0].numOut = 10;
userABC[0].myArray = new double[1];
userABC[0].myArray[0] = myInput;
Although you definetly need to study some object oriented coding before doing + you should read some basic java tutorial as well
As others have stated, there was no instantiation of the 0th object and therefore you had a runtime error. You could also do this:
public ABCout[] GetABC( double myInput ) throws Exception {
ABCout[] userABC = new ABCout[3];
ABCout current = new ABCout();
current.numOut = 10;
current.myArray = new double[1];
current.myArray[0] = myInput;
userABC[0] = current;
return userABC;
}

Categories