Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java class called ELEMENT for SPARSE VECTOR: Since the elements of a spa

ID: 3923404 • Letter: W

Question

Write a Java class called ELEMENT for SPARSE VECTOR:

Since the elements of a sparse vector are a pair of numbers, it is logical to design a structure to store an element of a vector. Write a class called Element which stores the index and value of an element of a vector. The data type of the index is int and the data type of the value is double.

A.The following are the only methods of the Element class:

B.The constructor for the class.

C.The get and set methods for the index.

D.The get and set methods for the value.

E.The Element class implements the Comparable interface:

which would allow the Element class to implement the compareTo method to compare one element with another element in order to easily sort the elements of a sparse vector in the proper order, the element with the smallest index up to the element with the largest exponent.

F.The toString method to properly print an element. For example, if the index of an element is 4 and the value is -36.4 then the toString method would print [4, -36.4].

Explanation / Answer

The program is as Follows :

public class Element implements Comparable<Element> {
   private int index;
   private double value;
  
   public Element(int index, double value) {
       this.index = index;
       this.value = value;
   }
   public int getIndex() {
       return index;
   }
   public void setIndex(int index) {
       this.index = index;
   }
   public double getValue() {
       return value;
   }
   public void setValue(double value) {
       this.value = value;
   }
   @Override
   public String toString() {
       return "[" + index + ", " + value + "]";
   }
   @Override
   public int compareTo(Element element) {
       return this.getIndex() - element.getIndex();
   }
  
   public static void main(String[] args) {
       Element element = new Element(2,36.4);
       System.out.println("Element :" + element);
   }
}

The sample output of above program is as follows :

Element :[2, 36.4]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote