0

i am trying to have an array of classes with 10 memebers

package localpackage;

import localpackage.Class;
public class School {
    int code;
    String name;
    Class[] classes = new Class[10];
    public School(int _code, String _name, Class _classes[]){
        code = _code;
        name = _name;
        classes = _classes;
    }
}

8
  • i want my constructor to only accept a list of 10 Commented Nov 29, 2021 at 14:45
  • Just a hint that java naming conventions recommend not using "_" before variables stackoverflow.com/questions/20677249/… Commented Nov 29, 2021 at 14:45
  • @javi3y again: what is your question? if you don't want the other parameters, delete them. If you want the array to be exactly sized ten, throw an exception if it has any other size Commented Nov 29, 2021 at 14:47
  • this is my first time writing java code sorry i didn't know i shouldn't do it Commented Nov 29, 2021 at 14:47
  • So if I understand correctly you want to ensure in the constructor that the array classes[] has a length of 10 ? Commented Nov 29, 2021 at 14:48

2 Answers 2

1

It seems you want to ensure a minimum size of a variable in the constructor. Take a look here, you will find what you need:

set minimum size of a variable array in the constructor

To name some of the solutions here, you can either directly check it with something like:

    if (name.length() < 12){
        throw new IllegalArgumentException("name must have at least 12 characters");
    }

Or you can move the check to a seperate Method and call it from the constructor.

Finally, you can use annotations like:

class Kingdom {
    @MinLength(12)
    private String name;

    ...
}

But then you need to create the Annotation class and implement the behaviour yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

You can either use ArrayList and define your 10 items :

     List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        arr.add(6);
        arr.add(7);
        arr.add(8);
        arr.add(9);
        arr.add(10);

Or from array :

         ArrayList<String> gfg = new ArrayList<String>(
            Arrays.asList(1,2,3,4,5,6,7,8,9,10));

Or use a nCopy :

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(10, new ItemsToCreate());

Or you can use a for loop

How can I initialize an ArrayList with all zeroes in Java?

2 Comments

This will probably be usefull for him to ensure he can pass arrays of a min length, however, he was asking about how to enforce variables passed to the constructor have a minimum length.
Oh, I didnt saw that. Hope it will help anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.