0

I want to assign some value in a 2D array.

I have 2 attributes called product and price.

iPad 999.9
iPod 123.4
iPhone 432.1

In 1-D array, I know how to assign the product value.

   String[] product = {"iPad", "iPod", "iPhone"};

However, in 2D array, if I assign like this:

String[][] array = new String[3][1];
array[0][1] = "iPad";

How can I assign the float number into the array?

Also, I have a question for sorting.

Since I declare the type of 2D array as String.

Can I sort the float price using this array?

Or I need to declare another array to do the sorting? Thank

1 Answer 1

8

You will save yourself lots of trouble, if you use objects instead of arrays to store products. E.g.,

class Product {
    String name;
    double price;
}

(add access modifiers, setters/getters and constructors if necessary)

Now you can access array of products easily without type conversions.

Product[] array = new Product[3];
array[0] = new Product();
array[0].name = "iPad";
array[0].price = 123.4;

Or, if you add constructor,

    Product[] array = {
        new Product("iPad", 123.4),
        new Product("iPod", 234.5),
        new Product("iPhone", 345.6)
    };

To allow sorting, you can implement Comparable interface and then call Arrays.sort(myProductArray):

class Product implements Comparable<Product> {
    String name;
    double price;

    public int compareTo(Product p) {
        return ((Double) price).compareTo(p.price);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend taking advantage of generics and making Product extend Comparable<Product>.

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.