Question: You are given a class Element which represents a chemical element. Copy it from Codecheck. An Element has a String name and a double atomicWeight

You are given a class Element which represents a chemical element. Copy it from Codecheck.

An Element has a String name and a double atomicWeight

Modify Element to implement the Comparable interface from the Java Library. Do not write your own interface. One Element comes before another if its atomic weight is smaller. It comes after if its atomic weight is greater. If the Elements have the same atomic weight, the one whose name comes first in alphabetical order comes first. (My apologies to chemistry majors if this is not entirely accurate. Just do the Java and don't worry about the chemistry.

Element.java

/** * Models a chemical element with a name and an atomic weight */ public class Element { private String name; private double atomicWeight; /** * Constructs a new chemical element * @param name the Element's name * @param weight the Element's atomic weight */ public Element(String name, double weight) { this.name = name; atomicWeight = weight; } public String getName() { return name; } public double getAtomicWeight() { return atomicWeight; } }

ComparableRunner.java

import java.util.Arrays; /** * Test compareTo method in Element */ public class ComparableRunner { public static void main(String[] args) { Element[] elements = { new Element("Uranium", 238.02), new Element("Potassium", 39.51), new Element("Nickel", 58.79), new Element("Argon", 39.51), new Element("Mercury", 200.59), new Element("Cobalt", 58.79) }; Arrays.sort(elements); for(Element e : elements) { System.out.println(e.getName() + " " + e.getAtomicWeight()); } } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!