If you were to get these questions on a test and could not use a computer to ans
ID: 3850246 • Letter: I
Question
If you were to get these questions on a test and could not use a computer to answer this question, only pen and paper.
How would you answer them? Please explain in detail and with step-by-step on how to approach questions like these :)
A class Association defines an association between a key and a corresponding element. An object of the class can be created and used like this: Association Integer, String new Association (new Integer (5), new String ("five")) Integer a. get Key String e a. getElement System.out println a k e) When this code fragment is executed, the following printout is obtained: 5 five 5, five A class Associations manages collections of associations in various ways. It contains a method findElement, that receives a list of associations and a key. The method finds the association in the list that has this key, and returns the corresponding element. You can use the method findElement like this: assoc new java util ArrayList java util. ListExplanation / Answer
Explanation :
1. Define the class Assciation and define constructor for setting the fileds and provide the getter methodes to access the both fields.
2. Define the Associations class which is having static method findElement() which can be called without making the instance of the Associations class
---------------------------------------------------------------------------------------------------------------------------------------------------------
package org.jay.chegg.july;
import java.util.ArrayList;
import java.util.List;
class Association {
private Integer key;
private String element;
/**
* @param key
* @param value
*/
public Association(Integer key, String element) {
this.key = key;
this.element = element;
}
/**
* @return the key
*/
public Integer getKey() {
return key;
}
/**
* @return the element
*/
public String getElement() {
return element;
}
}
class Associations {
/**
*
* @param list
* @param key
* @return
*/
public static String findElement(List<Association> list, Integer key) {
String value = null;
if (list != null && list.size() > 0) {
for (Association obj : list) {
if (obj.getKey() == key) {
value = obj.getElement();
break;
}
}
}
return value;
}
}
public class AssociationDemo {
public static void main(String[] args) {
// creating the instance of association
Association a = new Association(7, "Seven");
Association a1 = new Association(9, "Nine");
Association a2 = new Association(10, "Ten");
List<Association> list = new ArrayList<>();
// adding to the arraylist
list.add(a);
list.add(a1);
list.add(a2);
// searching through the list and returning the value
String element = Associations.findElement(list, 7);
System.out.println(element!=null ? element : "element not found");
}
}
---------------------------------------------------------------Output-----------------------------------------------------------------------
Seven