Question

Describe the operation of the enhanced for loop and explain why it’s especially useful with arrays....

  • Describe the operation of the enhanced for loop and explain why it’s especially useful with arrays.
  • Explain when you need to implement the Comparable interface in a class you create.
  • Describe the difference between a rectangular array and a jagged array, and explain the difference in how you create them.
  • Describe the similarities and differences between arrays and collections.
  • Name the two main types of collections defined by the collection framework and explain how they differ.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. Enhanced For Loop:

The main advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element one by one.

Syntax:

for(data_type variable : array | collection){  

//body of for-each loop  

}  

Example:

class ForEachExam{  

public static void main(String args[]) {  

int arr[]={1,3,14,4};  

for(int i:arr){  

System.out.println(i);  

}   }  }  

2. Comparable Interface:

Java Comparable interface is used to order the objects of the custom-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.

Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.sort (and Arrays.sort).

Using Comparable interface, we can sort the elements of:

  1. String objects
  2. Wrapper class objects, for example Integer, Long etc
  3. User defined custom objects

Syntax:

public interface Comparable<T>

{

    public int compareTo(T o);

}

Example:

Student.java

class Student implements Comparable<Student>{
int rollno;
String name;
int age;
  
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
  
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

Main Class to test:

TestSort1.java

import java.util.*;

public class TestSort1 {
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
  
Collections.sort(al);

for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}

4. Differences between arrays and collections

  1. Arrays are fixed in size but Collections are dynamic in size.
  2. With respect to memory arrays are not good to use but with respect to memory Collections are better to use.
  3. With respect to performance its better to use arrays but with respect to performance collection are not good to use.
  4. Arrays can hold only homogeneous elements but collections can hold both homogeneous and heterogeneous elements
  5. Arrays don't have ready made methods but collections have ready made data structures and methods.
  6. Arrays can hold both primitives and wrapper objects but collections can hold only objects.

5. Collection Framework

Main Types are:

1. List

Lists represents an ordered collection of elements. Using lists, we can access elements by their integer index (position in the list), and search for elements in the list. index start with 0, just like an array.

Some useful classes which implement List interface are – ArrayList, CopyOnWriteArrayList, LinkedList, Stack and Vector.

2. Set

Sets represents a collection of sorted elements. Sets do not allow the duplicate elements. Set interface does not provides no guarantee to return the elements in any predictable order; though some Set implementations store elements in their natural ordering and guarantee this order.

Some useful classes which implement Set interface are – ConcurrentSkipListSet, CopyOnWriteArraySet, HashSet, LinkedHashSet and TreeSet.

3. Map

The Map interface enable us to store data in key-value pairs (keys should be immutable). A map cannot contain duplicate keys; each key can map to at most one value.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Some useful classes which implement Map interface are – ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, Properties, TreeMap

Add a comment
Know the answer?
Add Answer to:
Describe the operation of the enhanced for loop and explain why it’s especially useful with arrays....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Questions 1. How do conceptual frameworks of accounting attempt to create a theory of accounting? Describe...

    Questions 1. How do conceptual frameworks of accounting attempt to create a theory of accounting? Describe the components of the IASB Framework and how it contributes to a theory of accounting. 2. Some people argue that there is no need for a general theory of accounting as established in a conceptual framework. They say there is no overall theory of physics. biology, botany or psychology, so there is no need for an overall theory of accounting. Furthermore, attempts to develop...

  • SHORT ANSWER QUESTIONS Part 1 Classes Abstraction: What is Abstraction in terms of representation? Specifically what...

    SHORT ANSWER QUESTIONS Part 1 Classes Abstraction: What is Abstraction in terms of representation? Specifically what choices does one make when creating a class that is an example of Abstraction? Encapsulation: What is encapsulation? What is information hiding? What does a public interface to a class consist of (not in the sense of actual java interfaces but what the client uses to manipulate objects of the class) What is an object of a class? What is the constructor? How do...

  • Zipcar: “It’s Not About Cars—It’s About Urban Life” Imagine a world in which no one owns...

    Zipcar: “It’s Not About Cars—It’s About Urban Life” Imagine a world in which no one owns a car. Cars would still exist, but rather than owning cars, people would just share them. Sounds crazy, right? But Scott Griffith, CEO of Zipcar, the world’s largest car-share company, paints a picture of just such an imaginary world. And he has nearly 800,000 passionate customers—or Zipsters, as they are called—who will back him up. Zipcar specializes in renting out cars by the hour...

  • Amazon to Competition: We Will Crush You! Amazon to Employees: We Will Churn You! Globally, Amazon...

    Amazon to Competition: We Will Crush You! Amazon to Employees: We Will Churn You! Globally, Amazon is one of the largest and most successful companies in any industry. Technological innovation has contributed to its success, as has its employee acquisition practices, which are exceptionally high. The question is what has allowed this company to thrive and maintain its success? This activity is important because it shows how companies like Amazon hire based on personality and individual differences. Such companies place...

  • what discuss can you make about medicalization and chronic disease and illness? Adult Lealth Nursing Ethics...

    what discuss can you make about medicalization and chronic disease and illness? Adult Lealth Nursing Ethics mie B. Butts OBJECTIVES After reading this chapter, the reader should be able to do the following: 1. Explore the concept of medicalization as it relates to the societal shift away from physician predominance of the 1970s. 2. Differentiate among the following terms: compliance, noncompliance, adherence, nonadherence, and concordance. 3. Examine cultural views with regard to self-determination, decision making, and American healthcare professionals' values...

  • I need help with my very last assignment of this term PLEASE!!, and here are the instructions: After reading Chapter T...

    I need help with my very last assignment of this term PLEASE!!, and here are the instructions: After reading Chapter Two, “Keys to Successful IT Governance,” from Roger Kroft and Guy Scalzi’s book entitled, IT Governance in Hospitals and Health Systems, please refer to the following assignment instructions below. This chapter consists of interviews with executives identifying mistakes that are made when governing healthcare information technology (IT). The chapter is broken down into subheadings listing areas of importance to understand...

  • please read instructions on the first picture and follow it Discussion Board: Chapter 1 Due: Jun...

    please read instructions on the first picture and follow it Discussion Board: Chapter 1 Due: Jun 28, 2019 at 11:59 PM Please read the article titled Evolution of Operations Planning and Control: from production to supply chains In at least three paragraphs, describe how and why the focus of operations planning and control has changed over time. While one might argue that answers consisting of sentences quoted from articles do not represent plagiarism, I do not consider them acceptable, and...

  • please read instructions on the first picture and follow it Discussion Board: Chapter 1 Due: Jun...

    please read instructions on the first picture and follow it Discussion Board: Chapter 1 Due: Jun 28, 2019 at 11:59 PM Please read the article titled Evolution of Operations Planning and Control: from production to supply chains In at least three paragraphs, describe how and why the focus of operations planning and control has changed over time. While one might argue that answers consisting of sentences quoted from articles do not represent plagiarism, I do not consider them acceptable, and...

  • Chapter overview 1. Reasons for international trade Resources reasons Economic reasons Other reasons 2. Difference between...

    Chapter overview 1. Reasons for international trade Resources reasons Economic reasons Other reasons 2. Difference between international trade and domestic trade More complex context More difficult and risky Higher management skills required 3. Basic concept s relating to international trade Visible trade & invisible trade Favorable trade & unfavorable trade General trade system & special trade system Volume of international trade & quantum of international trade Commodity composition of international trade Geographical composition of international trade Degree / ratio of...

  • How can we assess whether a project is a success or a failure? This case presents...

    How can we assess whether a project is a success or a failure? This case presents two phases of a large business transformation project involving the implementation of an ERP system with the aim of creating an integrated company. The case illustrates some of the challenges associated with integration. It also presents the obstacles facing companies that undertake projects involving large information technology projects. Bombardier and Its Environment Joseph-Armand Bombardier was 15 years old when he built his first snowmobile...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT