0

I need to overload constructor of the BigInteger class to create an instance of VeryLong from int and long. Here is my code:

    private ArrayList<Long> A = new ArrayList<>();

    private VeryLong(int n) {
        while (n > 0) {
            A.add(long()(n % 10));
            n /= 10;
        }

        while (!A.isEmpty()) {
            System.out.println(A.get(0));
            A.remove(0);
        }
    }

    private VeryLong(long n) {
        while (n > 0) {
            A.add(n % 10);
            n /= 10;
        }

        while (!A.isEmpty()) {
            System.out.println(A.get(0));
            A.remove(0);
        }
    }

If I define A as ArrayList of Long there goes error in first constuctor. Similarly, it's error in add() method in second, if i define A as Vector<Integer> A = new Vector<Integer>();. How can I fix it?

4
  • You get the error with the code you've shown, or when you change your code to use Vector? Can we see the error? Where do BigInteger constructors come into this? Commented Oct 15, 2019 at 23:12
  • 2
    Why do you even need separate overloads for int and long? The long one would do the same as the int one. And why add to an ArrayList only to remove it all again? Commented Oct 15, 2019 at 23:22
  • You're using the ArrayList to store digits of the number in the range 0-9. You don't need it to be ArrayList<Long>, ArrayList<Integer> (or ArrayList<Byte>) is just fine for both constructors. You need to learn the proper casting syntax. Commented Oct 15, 2019 at 23:44
  • These are pretty strange constructors. They fill up a member variable (A) with digits and then empty it again. That is, they 'construct' nothing useful. Commented Oct 15, 2019 at 23:51

1 Answer 1

1

The error in the constructor is due to the wrong casting syntax:

It should be A.add((long)(n % 10));, not A.add(long()(n % 10));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.