How to store an array of pairs in Java?

前端 未结 9 1336
日久生厌
日久生厌 2020-12-15 06:51

I am new to Java, I want to store an array of pair of doubles. My code looks like this:

import java.util.ArrayList;
import java.util.Map.Entry;

List

        
9条回答
  •  执笔经年
    2020-12-15 07:42

    You don't want to use Entry it's an INTERFACE, not a CLASS. That interface is used by an implementations of Set when you call entrySet() on a class that implements Map. It basically lets you manipulate the implemented Map as though it were a Set.

    What you would do (but can't) is this. If you try to do this you'll see a compiler error along the lines of "Cannot instantiate the type Map.Entry". That's because Map.Entry is an interface, not a class. An interface doesn't contain any real code, so there's no real constructor to run here.

    Entry pair = new Entry();
    

    If you look at the below docs you can clearly see at the top that it's a "Interface Map.Entry" which means it's an interface. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Map.Entry.html

    What you should do instead of trying to instantiate an interface, which is impossible, is create your own class called Pair. Something like this. Remember to change the package if you use the below code.

    package org.mike.test;
    
    public class Pair {
        private double x = 0.0;
        private double y = 0.0;
    
        public Pair(double x, double y)
        {
            this.x = x;
            this.y = y;
        }
    
        public Pair()
        {
    
        }
    
        public double getX() {
            return x;
        }
    
        public void setX(double x) {
            this.x = x;
        }
    
        public double getY() {
            return y;
        }
    
        public void setY(double y) {
            this.y = y;
        }
    
    
    }
    

    After writing your Pair class your code will now look like this.

    package org.mike.test;
    
    import java.util.ArrayList;
    import org.mike.test.Pair; //You don't need this if the Pair class is in the same package as the class using it
    
    public class tester {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            ArrayList values = new ArrayList();
            Pair pair = new Pair();
            // set pair values:
            pair.setY(3.6);
            pair.setX(3.6);
            values.add(pair);
        }
    
    }
    

提交回复
热议问题