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));
Related
Just out of curiosity, based on that code is there a way to that instead of
int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };
can be written under a for like this
for(int i=0;i<obj.ar.length;i++)
or to just combine all arrays of obj[].ar using obj.length in one 2 dimenstional array?
public class Main
{
public static void main(String[] args)
{
int nb = 3;
arr[] obj = new arr[nb];
for(int i=0;i<obj.length;i++)
{
obj[i] = new arr(i+2);
}
int [][]d = { obj[0].ar , obj[1].ar , obj[2].ar };
for(int i=0;i<d.length;i++)
{
for(int j=0;j<d[i].length;j++)
System.out.print(d[i][j]+"\t");
System.out.println();
}
}
}
class arr
{
int []ar;
arr(int nb)
{
ar = new int[nb];
for(int i=0;i<ar.length;i++)
ar[i]=i;
}
}
Java arrays must always have a determined size upon creation.
Notice you are always setting nb in the calls to new arrays, or by using the {} instantiator which will count the number of objects statically.
What you are asking for is probably what ArrayList is meant to achieve. It will grow as you go, while having an array implementation behind the scenes. If the contents cannot fit in the array, a new - larger - array is created to fit them all. You won't notice this while using it though.
ArrayList<ArrayList<Integer>> obj = new ArrayList<>();
obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
obj.add(new ArrayList<>());
// There are now three empty lists, in the main list.
Since java 9, you can use some extra helper methods:
List<List<Integer>> obj = List.of(
List.of(1,2,3),
List.of(2,3,4)
);
If you want, you can implement you own ArrayList class, it's not that hard!
I recently watched a dynamic programming tutorial on Youtube explaining dynamic programming but the Tutor solved problems in JavaScript. I, on the other hand, use Java for data structures and algorithms. While implementing dynamic programming to solve a question. I discovered that I got the solution to the problem when using int[] but had wrong answer when using ArrayList<Integer> because somehow, the ArrayList already stored in the HashMap was being modified internally.
Question:
Write a function bestSum(targetSum, numbers) that takes in a targetSum and an array of numbers as arguments and returns an array containing the shortest combination of numbers that add up to exactly the target sum.
Example:
bestSum(7,new int[]{2,1,3}) => [3,3,1] //other possibilities but not answer:[2,2,2,1], [1,1,1,1,1,1,1], [2,2,1,1,1], etc
bestSum(100,new int[]{2,5,25}) => [25,25,25,25]
Code using int[]:
public class Persist {
public static HashMap<Integer,int[]> memo = new HashMap<>();
public static int[] bestSum(int n, int[] arr){
if(memo.containsKey(n)){
//System.out.printf("From memo: %d->"+ Arrays.toString(memo.get(n)) +"%n",n);
return memo.get(n);
}
if(n==0)return new int[0];
if(n<0)return null;
int[] minn = null;
for(int i = 0;i<arr.length;i++){
//recursion
var temp = bestSum(n-arr[i],arr);
if(temp!=null){
// ttemp is used to add arr[i] to the initial arr <<temp>>
int[] ttemp = new int[temp.length+1];
System.arraycopy(temp,0,ttemp,0,temp.length);
ttemp[temp.length] = arr[i];
temp = ttemp;
if(minn==null||temp.length<minn.length){
minn = temp;
}
}
}
//System.out.println(n+": "+minn);
memo.put(n,minn);
//System.out.println(memo.get(n));
return minn;
}
public static void main(String[] args){
System.out.println(Arrays.toString(bestSum(7, new int[]{2,1,3})));
}
}
Code using ArrayList<Integer> :
public class Persist {
public static HashMap<Integer,ArrayList<Integer>> memo = new HashMap<>();
public static ArrayList<Integer> bestSum(int n, int[] arr){
if(memo.containsKey(n)){
//System.out.printf("From memo: %d->"+ memo.get(n)+"%n",n);
return memo.get(n);
}
if(n==0)return new ArrayList<>();
if(n<0)return null;
ArrayList<Integer> minn = null;
for(int i = 0;i<arr.length;i++){
var temp = bestSum(n-arr[i],arr);
if(temp!=null){
temp.add(arr[i]);
if(minn==null||temp.size()<minn.size()){
minn = temp;
}
}
}
//System.out.println(n+": "+minn);
memo.put(n,minn);
//System.out.println(memo.get(n));
return minn;
}
public static void main(String[] args){
System.out.println(bestSum(7,new int[]{2,1,3}));
}
}
The only differences between the two code snippets is the use of int[] and ArrayList<Integer> respectively, but one works and the other doesn't. I will like to know why, thanks.
Link to Youtube explanation of bestSum()
It's easy to get caught up with memoization and dynamic programming and forget that about pass by reference and pass by value. The key difference here to remember is that ArrayList is pass by reference.
If you debug and look at your hashmap memo, you see that the sizes of the int[] only reaches up to 3, whereas in the arraylist hashmap most of the values has a size of 7
I had a similar problem: casting does not work on nested list object type and returns empty lists (List<List<Integer>>)
I have a homework task where I am required to write only 1 method (a member of class MainClass) which creates simultaneously more than one type of array -with only using this method. I tried to create a method that returns the corresponing type but then it can only be done with one type of array (see the commented code /function/). My question is how can I create sort of a templated function which returns all types at once my attemp is below, /but sadly not working/?
import java.lang.reflect.Array;
import java.sql.SQLOutput;
import java.util.Arrays;
public class MainClass {
//ще направим отделни методи за класовете
/*public int [] returnArr(){
int [] ar = new int[10];
return ar;
}*/
public void createArray(){
//here I create more than one type of array:
int []ar = new int[10];
String[] str = new String[10];
double [] dbl = new double[10];
}
}
class Test{
public static void main(String[] args) {
MainClass mcl = new MainClass();
/*int [] ia = mcl.returnArr();
for (int i = 0;i<10;i++){
Arrays.fill(ia,0,9,8);
}*/
mcl.createArray();
//here the ar[] array is not accessible
Arrays.fill(ar,0,9,0);
for (int i:ar){
System.out.println(i);
}
}
}
I hope you are practicing OOPs. In Java , its not possible for a method to return multiple types. You have mentioned, you need to create multiple types of arrays using a single method. You can go by 2 methods here.
The Object oriented way - use the instance variables & initialize them in one method. It would be something like below
public class MainClass {
private int[] intArray;
private String[] strArray;
private double[] dblArray;
public void createArray() {
this.intArray = new int[10];
this.strArray = new String[10];
this.dblArray = new double[10];
}
}
And then you can use some getter methods to access the arrays.
Return array of arrays - You can return multiple values as a composite type array. For example array of java.lang.Object. Since Object is the parent class of everything in Java, an array of Object can hold any types. then your method would look like
public Object[] createArray()
{
int[] intArray = new int[10];
String[] strArray = new String[10];
double[] dblArray = new double[10];
Object[] returnArray = new Object[] { this.intArray, this.strArray, this.dblArray };
return returnArray;
}
Now in the Object array that is returned
Object[] arrays = mcl.createArray();
// arrays[0] is an integer array, arrays[1] is string array and so on.
int[] arr = arrays[0];
Now you can use the arrays in the manner you need. Hope you are clear on the concept.
My class Test2 has a method to return area. It accepts a variable number of argument (Varargs) and I am trying to add alternative Varargs into the array lengthOfSide and breadthOfSide using a for loop but I am getting an ArrayOutofBoundException. Why am I getting this and how do I fix it?
class Test2 {
public double returnArea(double... corner){
double[] lengthOfSide = {};
double[] breadthOfSide = {};
int i = 0;
for(double x : corner){
lengthOfSide[i] = x;
breadthOfSide[i] = x;
System.out.println(lengthOfSide[i]);
System.out.println(breadthOfSide[i]);
i++;
}
}
}
public class Test1 {
public static void main(String args[]){
Test2 total = new Test2();
total.returnArea(34.2,22.3,332.2,223.3,22.4);
}
}
Java arrays have a fixed length. You currently create two arrays of length 0. Change
double[] lengthOfSide = {};
double[] breadthOfSide = {};
to something like
double[] lengthOfSide = new double[corner.length];
double[] breadthOfSide = new double[corner.length];
You are basically trying to modify an existing array which is not allowed...
Arrays in java are fixed sized and you can't modify them after you have created them.
basically,
double[] lengthOfSide = {};
double[] breadthOfSide = {};
this lines created an array for you (empty array).
where as in loop you are trying to assign a value to index in array that does not exist.
lengthOfSide[i] = x;
breadthOfSide[i] = x;
result is excetion.
if You want to achieve what i guess is right you should initialize it to some length you want ie. corner.length
so it should be,
double[] lengthOfSide = new double[corner.length];
double[] breadthOfSide = new double[corner.length];
also if you still want to go with the same flow try considering using arraylist for purpose.
You should specify the length of array when you create one. And after this you can't change array length. There are 2 arrays with length of 0 in your example.
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 !!!