The document discusses using collections like ArrayList in Java. It explains that collections allow storing an arbitrary number of objects and provide functionality to add, remove and iterate over items. The document also demonstrates how to use an ArrayList to organize music files by adding, getting and listing files. Iteration over collections using a for-each loop is described. Generic classes are introduced as a way to specify the type of objects a collection contains.
Collections and its types in C# (with examples)Aijaz Ali Abro
Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple array.
Collections and its types in C# (with examples)Aijaz Ali Abro
Learn step by step c# collections with easy examples. Learn generic, non-generic and specialized collections along with easy and great examples. Learn about arraylist, queue class,stack class and more. Difference between generic and non-generic collections. Difference between arraylist and simple array.
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
To learn important concept of Collection and its handling plus its advantages and different class & child class of Collection and their implementations. Important interview questions of the collection.
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
1.Collections
2.Collection is a java object that is used to store
homogeneous & hetrogeneous , Duplicate & unique
objects with out size limitation for carrying multiple
objects At a time from one application to another
application among multiple layers of MVC
architecture as method arguments and return type
Problem with Object[] to collect objects:
1.It allows us to store only same type of elements
2.It is fixed in size
3.Doesnot inbuilt methods for performing different
operations
3.All collection classes are defined in java.util package
Sun developed many collection classes among them 13 are important , they
are
ArrayList HashSet HashMap
Vector LinkedHashSet LinkedHashMap
Stack TreeSet TreeMap
LinkedList Hashtable
PriorityQueue Properties
Some helper/utility classes
Collections Scanner Locale Date
Arrays StringTockenizer ResourceBundle Calender
Random Currently GregoroanCale
der
4.We can collect objects in 2 ways
1.In array format- in this format object does not have identity
2.In (key , value) pair format- in this format object has identity
In java 1.0 version SUN only introduced 2 classes to collect
objects in above formats
Vector :It stores objects in array format
Hashtable: It stores objects in (key, value ) pair format
In java 1.2 version all collections are collectively called as
Collection framework
1.Collection hierarchy
2.Map hierarchy
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
To learn important concept of Collection and its handling plus its advantages and different class & child class of Collection and their implementations. Important interview questions of the collection.
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
1.Collections
2.Collection is a java object that is used to store
homogeneous & hetrogeneous , Duplicate & unique
objects with out size limitation for carrying multiple
objects At a time from one application to another
application among multiple layers of MVC
architecture as method arguments and return type
Problem with Object[] to collect objects:
1.It allows us to store only same type of elements
2.It is fixed in size
3.Doesnot inbuilt methods for performing different
operations
3.All collection classes are defined in java.util package
Sun developed many collection classes among them 13 are important , they
are
ArrayList HashSet HashMap
Vector LinkedHashSet LinkedHashMap
Stack TreeSet TreeMap
LinkedList Hashtable
PriorityQueue Properties
Some helper/utility classes
Collections Scanner Locale Date
Arrays StringTockenizer ResourceBundle Calender
Random Currently GregoroanCale
der
4.We can collect objects in 2 ways
1.In array format- in this format object does not have identity
2.In (key , value) pair format- in this format object has identity
In java 1.0 version SUN only introduced 2 classes to collect
objects in above formats
Vector :It stores objects in array format
Hashtable: It stores objects in (key, value ) pair format
In java 1.2 version all collections are collectively called as
Collection framework
1.Collection hierarchy
2.Map hierarchy
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR CONVERGENCEJerry Foss
This presentation proposes in-video personalisation using object-based media for the insertion of externally sourced video placements into broadcast content (real-time or on-demand). Placement content is selected in accordance with viewer profiles, and may be produced independently of the source video.
Using this this technology user-object interaction is also possible. Use cases, include personalised product placement, training, education and accessibility for hearing and visually impaired viewers. The technology specifically fits existing distribution platforms (cable, satellite, DTTV, IPTV/OTT) with minimal infrastructure upgrade.
This presentation is meant to discuss the basics of video compression like DCT, Color space conversion, Motion Compensation etc. It also discusses the standards like H.264, MPEG2, MPEG4 etc.
Recursively Searching Files and DirectoriesSummaryBuild a class .pdfmallik3000
Recursively Searching Files and Directories
Summary
Build a class and a driver for use in searching your computer’s secondary storage (hard disk or
flash memory) for a specific file from a set of files indicated by a starting path. Lets start by
looking at a directory listing. Note that every element is either a file or a directory.
Introduction and Driver
In this assignment, your job is to write a class that searches through a file hierarchy (a tree) for a
specified file. Your FindFile class will search a directory (and all subdirectories) for a target file
name.
For example, in the file hierarchy pictured above, the file “lesson.css” will be found once in a
directory near the root or top-level drive name (e.g. “C:\\”) . Your FindFile class will start at the
path indicated and will search each directory and subdirectory looking for a file match. Consider
the following code that could help you build your Driver.java:
String targetFile = “lesson.css”;
String pathToSearch =”
C:\\\\WCWC”; FindFile finder = new FindFile(MAX_NUMBER_OF_FILES_TO_FIND);
Finder.directorySearch(targetFile, pathToSearch);
File Searching
In general, searching can take multiple forms depending on the structure and order of the set to
search. If we can make promises about the data (this data is sorted, or deltas vary by no more
than 10, etc.), then we can leverage those constraints to perform a more efficient search. Files in
a file system are exposed to clients of the operating system and can be organized by filename,
file creation date, size, and a number of other properties. We’ll just be interested in the file
names here, and we’ll want perform a brute force (i.e., sequential) search of these files looking
for a specific file. The way in which we’ll get file information from the operating system will
involve no ordering; as a result, a linear search is the best we can do. We’d like to search for a
target file given a specified path and return the location of the file, if found. You should sketch
out this logic linearly before attempting to tackle it recursively.
FindFile Class Interface
FindFile(int maxFiles): This constructor accepts the maximum number of files to find.
void directorySearch(String target, String dirName): The parameters are the target file name to
look for and the directory to start in.
int getCount(): This accessor returns the number of matching files found
String[] getFiles(): This getter returns the array of file locations, up to maxFiles in size.
Requirements
Your program should be recursive.
You should build and submit at least two files: FindFile.java and Driver.java.
Throw an exception (IllegalArgumentException) if the path passed in as the starting directory is
not a valid directory.
Throw an exception if you\'ve found the MAX_NUMBER_OF_FILES_TO_FIND and catch and
handle this in your main driver. Your program shouldn\'t crash but rather exit gracefully in the
unusual situation that we\'ve discovered the maximum number of files we were interest.
core & advanced java classes in Mumbai
best core & advanced java classes in Mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion, etc. can be achieved by Java Collections.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.).
Describes the concept of ADTS and illustrates the concept with three o.docxearleanp
Describes the concept of ADTS and illustrates the concept with three of the most common abstract data types.
Solution
An abstract data type is a set of values, some of which may be distinguished as constants, together with a collection of operations involving members of the set.The primary objective is to seperate the implementation of the abstract data types from their function.The program must know what the operations do.
List,stack and queues are three fundamental data structures.When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.Depending on the data type, your variable is allocated that type of memory. There are two types of memory allocation: stack memory and heap memory
Stack memory stores data types like int , double , Boolean etc. While heap stores data types like string and objects.Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer\'s RAM .Variables allocated on the stack are stored directly to the memory and access to this memory is very fast.When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order.Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.
The Queue works like FIFO system , a first-in, first-out collection of Objects. Objects stored in a Queue are inserted at one end and removed from the other. The Queue provide additional insertion, extraction, and inspection operations. We can Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is we will get the reference of first item ) item from Queue. Queue accepts null reference as a valid value and allows duplicate elements.
A list is a collection of items that can be accessed by index and provides functionality to search, sort and manipulate list items. This can store any data types to create a list.The List class can be used to create any type including a class. In this article, we will see how to create a list of a class with several properties.
.
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
The second programming assignment (HW4) is designed to help you ga.docxoreo10
The second programming assignment (HW4) is designed to help you gain
experience with object oriented programming in Java.
The given file for hw4, "hw4.given.tar.gz", is on the class web page.
To untar and unzip the file, execute
tar -xzvf hw4.given.tar.gz
It will expand to create a directory called hw4, which contains sub-
directories part0, ..., part9, one for each part of the assignment.
Each part has a Makefile. Don't modify them.
Main.java, which is different for each part, is used to test your code
by creating objects, invoking methods, etc.
As you did on the previous assignment, you'll be using the tester tool
for testing.
Proceed similarly to what you did on the previous programming
assignment:
cd part0
# add a bunch of code
make
# if make gives errors, fix them and make again.
../tester
# if tester gives errors, fix them and repeat this cycle.
In Part 7 (only), additional tests (in Main.java and correct output
files) check that the iterators' next() methods give an error if
they're invoked when no elements remain in their collection. (In
subsequent parts, such erroneous behavior results in an exception, so
the testing doesn't use these extra tests.)
Similar to the last assignment, each part builds off the last. When
you're finished with one part,
copy all .java files ***EXCEPT Main.java*** to the next part.
Then modify these copies to start your solution for the next part.
***Exception: again, don't copy Main.java from part to part.***
See the documentation on tester (on the class web page) for details on
its use.
As always, get started early to avoid the last minute rush!
ECS140A-F16-06 October 18, 2016
ASSIGNMENT 4: Java object oriented program
Due: October 27, 2016
Overview
The purpose of this assignment is for you to gain experience with object oriented programming in
Java: in particular, the ideas of inheritance, dynamic binding (virtual methods), overriding and
overloading methods, iterators (aka generators). It will also give you some exposure to how some
programming language features are implemented, i.e., what happens "behind the scenes" when
you execute a program. Although no language provides the exact features in this assignment, a
number of languages (e.g., Awk, Icon, LISP, CLU) do provide similar features. (In fact, you
could define a little language, using techniques from first program, that would contain features
like those in this assignment.)
Your program needs to provide several abstractions. The first abstraction is an Element, of which
there are three kinds: EBoolean, EInteger, and EString. The second abstraction is an EList of Ele-
ment; associated with the EList abstraction is EListIt, which iterates over a list. Details of these
are given below in each part of this assignment.
N.B., you are restricted as to how you write your code. See “Details” before you start coding.
1
ECS140A-F16-06 October 18, 20 ...
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
2. To learn how to use debugger to step the behavior of the program
To learn about object structures with collections – ArrayList.
To learn about ArrayList features and methods
To know what does generic classes mean
Iterations
2
3. The debugger is useful for gaining insights into program behavior
whether or not there is a program error.
The steps should follow in debugger:
◦ Set breakpoints.
◦ Examine variables.
◦ Step through code.
3
5. A collection of objects can store an arbitrary number of other
objects.
It is the notion of grouping things so that we can refer to them and
manage them all together.
A collection might be:
◦ large (all the students in a university)
◦ small (the courses one of the students is taking)
5
6. Many applications involve collection of objects:
Personal Organizer:
◦ Electronic calendars store event notes about appointments, meetings, birthdays, and
so on.
◦ New notes are added as future events are arranged, and old notes are deleted as
details of past events are no longer needed.
Library Catalogs:
◦ Libraries record details about the books and journals they own.
◦ The catalog changes as new books are bought and old ones are put into storage or
discarded.
Student Record System:
◦ Universities maintain records of students.
◦ Each academic year adds new records to the collection, while the records of those
who have left are moved to an archive collection.
◦ Listing subsets of the collection will be common: all the students taking Computing or
all the students due to graduate this year, for instance
6
7. Entries must be accessed efficiently
The number of items to be stored varies
◦ Need the ability to add and delete items
7
8. To understand this concept, we are going to write a class that can help
us organize our music files stored on a computer.
Our class won’t actually store the file details; instead, it will delegate
that responsibility to the standard ArrayList library class, which will save
us a lot of work.
Here are the basic operations we will have in the initial version of our
organizer:
◦ It allows tracks to be added to the collection.
◦ It has no predetermined limit on the number of tracks it can store, aside from
the memory limit of the machine on which it is run.
◦ It will tell us how many tracks are in the collection.
◦ It will list all the tracks.
We shall find that the ArrayList class makes it very easy to provide this
functionality from our own class.
8
9. Collections are known as parameterized or generic types.
Generic classes, in contrast to other classes we have seen so far, do not define
a single type in Java, but potentially many types.
ArrayList is a parameterized or generic type.
The ArrayList class, for example, can be used to specify an ArrayList of String,
an ArrayList of Person, an ArrayList of Rectangle, or an ArrayList of any other
class that we have available.
Each particular ArrayList is a separate type that can be used in declarations of
fields, parameters, and return values.
The type parameter says what we want a list of:
private ArrayList<Person> members;
private ArrayList<TicketMachine> machines;
9
10. Class libraries usually contain tried-and-tested collection classes.
We don’t have to write everything from scratch. Java calls its libraries,
packages.
◦ The java.util package contains classes for doing this.
10
12. An ArrayList is a dynamic data structure, meaning items can be
added and removed from the list.
Each item has an index.
Index values may change if items are removed (or further items
added).
We specify:
◦ the type of collection: ArrayList
◦ the type of objects it will contain: <String>
◦ private ArrayList<String> files;
We say, “ArrayList of String”.
12
13. The following figure illustrates how a MusicOrganizer object might
look with two filename strings stored in it; Object Structures with
Collection.
13
15. There are at least three important features of the ArrayList class that
you should observe:
◦ It is able to increase its internal capacity as required: as more items are
added, it simply makes enough room for them.
◦ It keeps its own private count of how many items it is currently storing.
Its size method returns that count.
size() accessor
It maintains the order of items you insert into it.
The add method stores each new item at the end of the list. You can
later retrieve them in the same order.
15
16. ArrayList implements list functionality (methods):
◦ add, get, remove, size, etc.
Once you have a new ArrayList objects, you can add elements to it
with the add method:
◦ listTest.add( "first item" );
◦ listTest.add( "second item" );
◦ listTest.add( "third item" );
◦ listTest.add( 7 );
16
17. Adding a new file
Returning the number of files
(delegation)
17
public class MusicOrganizer
{
private ArrayList<String> files;
...
public void addFile(String filename)
{
files.add(filename);
}
public int getNumberOfFiles()
{
return files.size();
}
...
}
18. Items in the list can be referenced by an Index number, and by using
the get method:
18
19. Index validity checkspublic void listFile(int index)
{
if(index >= 0 &&
index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
}
else {
// This is not a valid index.
}
} Retrieve and print the file name
Needed? (Error message?)
19
21. Using integers to index collections has a general utility:
◦ ‘next’ is index + 1
◦ ‘previous’ is index – 1
◦ ‘last’ is list.size() – 1
◦ ‘the first three’ is the items at indices 0, 1, 2
We could also think about accessing items in sequence: 0, 1, 2, …
21
22. Collections allow an arbitrary number of objects
to be stored
Class libraries usually contain tried-and-tested
collection classes
Java’s class libraries are called packages
We have used the ArrayList class from the
java.util package
22
23. Items may be added and removed
Each item has an index
Index values may change if items are removed
(or further items added)
The main ArrayList methods are
add, get, remove, and size
ArrayList is a parameterized or generic type
23
24. We often want to repeat some actions over and over
◦ e.g. “do this action for each student in the university”
◦ e.g. “do this action seventeen times”
◦ e.g. “do this action until this condition is true”
Java loops provide us with a way to control how many times we
repeat these actions
With collections, we often want to repeat things once for every
object in a particular collection
24
25. for(ElementType element : collection) {
loop body
}
For each element in collection, do the things in the loop body.
loop header
for keyword
Statement(s) to be repeated
Pseudo-code expression of the
actions of a for-each loop
General form of the for-each loop
25
26. /**
* List all file names in the organizer.
*/
public void listAllFilesForEachLoop()
{
for(String filename : files) {
System.out.println(filename);
}
}
for each filename in files, print out filename
26
27. Statements can be nested, giving greater selectivity:
public void findFiles(String searchString)
{
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
}
}
}
27
28. public String findFiles(String searchString)
{
for (String filename : files) {
if (filename.contains(searchString)) {
return filename; // return the first match if one is
found
}
}
return “”; //return empty string if NO match is found
}
28
29. Easy to write
Termination happens naturally
The collection cannot be changed
There is no index provided
◦ Not all collections are index-based
We can’t stop part way through
◦ Except when using a return statement
It provides ‘definite iteration’,
aka ‘bounded iteration’
29
30. The for-each loop is used whenever we need to perform some action
on every item in a collection:
view every one
change every one
check every one
select some or count some from every one
30
31. 1. Get first element of the collection files
2. Execute statement using that value
3. Get next element from the collection and repeat from 2
4. But if no elements left then stop
for (String filename : files) {
if (filename.contains(searchString)) {
System.out.println(filename);
}
}
31
32. We have seen how this results in structures of objects working
together to solve a common task.
Objects can create other objects, and they can invoke each other’s
methods. Understanding these object interactions is essential in
planning, implementing, and debugging applications.
We can use pen-and-paper diagrams, code reading, and debuggers
to investigate how an application executes or to track down bugs.
32
33. We have made good progress with the basics of organizing our
music collection. We can store the names of any number of music
files and even play them.
We have done this with relatively little coding effort, because we
have been able to piggyback on the functionality provided by library
classes: ArrayList from the standard Java library and a music player
that uses a third-party class library.
We have also been able to do this with relatively little knowledge of
the internal workings of these library classes; it was sufficient to
know the names, parameter types, and return types of the key
methods.
33
34. Barnes, David J., and Kölling, Michael. 2012. Objects First with
Java, A practical Introduction Using BlueJ (5th Edition). Boston:
Preston.
Liang, Y. Daniel. 2011. Introduction to Java Programming,
Comprehensive (8th Ed.) Prentice Hall.
http://www.tutorialspoint.com/java/java_decision_making.htm
http://www.homeandlearn.co.uk/java/java.html
34