Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize array of custom class objects? [duplicate]

Tags:

java

android

It sounds easy but i've been trying to do it for quite sometime, I want to initialize my custom class object array using curly braces

Here is the failed example:

class:

class Tranforminfo{
        int left;
        int top;
        int right;
        int bottom;
        float rorate;

        public Tranforminfo(int left, int top, int right, int bottom, float rorate) {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
            this.rorate = rorate;
        }
    }

Usage: (not correct)

// attempt 1 
Tranforminfo somedamn = new Tranforminfo[]{(1,2,3,4,5),(6,4,3,5,6)};

// attempt 2
Tranforminfo somedamn = new Tranforminfo[]{{1,2,3,4,5},{6,4,3,5,6}};

// attempt 3
Tranforminfo somedamn = new Tranforminfo[]((1,2,3,4,5),(6,4,3,5,6));

No luck so far help appreciated , i am coding in android(JAVA)

like image 754
Zulqurnain Jutt Avatar asked Aug 14 '16 19:08

Zulqurnain Jutt


People also ask

How do you initialize a custom array in Java?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.

How do you create an array of different objects in Java?

Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.


1 Answers

There is some ways to do it:

Transforminfo[] somedamn = 
    new Transforminfo[] { new Transforminfo(1,2,3,4,5),
                          new Transforminfo(6,4,3,5,6) };
Transforminfo[] somedamn = 
    { new Transforminfo(1,2,3,4,5), new Transforminfo(6,4,3,5,6) };  

First you create Transforminfo array link, then add new Transforminfo elements into.

It's like Integer []array = {1, 2, 3}, but you have to use constructor to create Transforminfo elements.

One more example to understand array of object creating. All way is equal.

String array[] = { new String("str1"), new String("str2") };
String[] array = { new String("str1"), new String("str2") };
String array[] = new String[] { new String("str1"), new String("str2") };
String[] array = new String[] { new String("str1"), new String("str2") };
like image 52
jisecayeyo Avatar answered Sep 18 '22 02:09

jisecayeyo