Showing posts with label collections in java. Show all posts
Showing posts with label collections in java. Show all posts

Friday, March 1, 2024

COLLECTIONS IN JAVA

 Collections in Java


  • FRAMEWORKS
  • ADVANTAGES OF JAVA COLLECTION FRAMEWORK
  • METHODS OF COLLECTION INTERFACE
  • LINKED LIST
  • VECTOR
  • STACK
  • QUEUE INTERFACE
  • SET INTERFACE
  • CLASSES THAT IMPLEMENT THE SET INTERFACE( HARSH SET, SORTED SET, MAP, ETC)

Java's Collection framework may be used to store and manage collections of objects.

Java Collections may be used for data operations such as sorting, searching, inserting, modifying, and removing. In Java, an object collection is called a collection. The Java Collection foundation includes classes and interfaces including Vector, LinkedList, Priority Queue, HashSet, LinkedHashSet, and TreeSet.

Framework in Java

An architecture that has already been created for a group of classes and interfaces is called a framework. It is not necessary to define a framework to add a new class or function. But with a perfect object-oriented design, there is always a framework with classes in it, so every class does the same job.

Java's unique collection structure is required

Arrays, vectors, and hash tables were the usual Java ways for objects (or collections) before the introduction of the collection framework (or JDK 1.2). All of these collections lacked a single, cohesive user interface. As a result, even while every collection aims to achieve the same general objective, each collection's implementation was decided upon independently of the others. Not to mention how hard it is for users to remember the distinct constructors, functions, and syntax of every collection class.

A nice example of this is the procedure for adding an element and a vector to a hash table.

Let's see an example here:

// why collection framework was needed

The Array, Vector, and Hash table collections had a standard member interface, which made it hard for programmers to design algorithms that could manage several types of collections. Another disadvantage is that since the majority of the 'Vector' methods are final, therefore we can't modify the 'Vector' class to create an equivalent collection. As a result, the Java development team created the Collection Framework in JDK 1.2 as a common interface to handle the aforementioned problems; this framework was used to standardize both the hash table and the outdated vectors.

Advantages of Java collection framework

Since the aforementioned disadvantages stem from the absence of a collecting framework, the following are advantages of having one.

When all classes that implement an application programming interface (API) utilize the same set of methods, that API is said to be consistent. This comprises, among other things, Set, LinkedList, Vector, and ArrayList.

reduces the developer's workload on the code by letting him focus on using the collection as efficiently as can rather than thinking about how it was designed. This successfully implements the core concept or features of object-oriented programming, which is sometimes referred to as abstraction.

Enhances the effectiveness and caliber of the program Since algorithms and data structures are supplied in a useful and efficient way—the programmer is not performing their job here—performance is enhanced. It is essential to think about how best to use a certain data structure. All he needs to do is employ the best implementation to significantly increase the efficiency of his algorithm or program.

Methods of collection interface


Collection interface

The collection interface is followed by every class that comprises the collection framework. It spells out how each set is to be done. Stated differently, a collection interface creates the basis upon which the entire framework is built.

Every subclass implements many of the methods available in the collection interface. void clean (), Boolean add All (Collection c), and Object obj are a few of these methods.

List interface

The list interface is a subset of the overall interface. These blocks allow us to store an ordered collection of items in a list-type data structure. It can hold several values in storage.

The List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. One cannot construct the List interface without first using it.

  1. List <data-type> list1= new ArrayList();  
  2. List <data-type> list2 = new LinkedList();  
  3. List <data-type> list3 = new Vector();  
  4. List <data-type> list4 = new Stack(); 

 

Iterable interface

The primary interface via which all collection classes communicate with one another is the Iterable interface. All Aggregate subclasses implement the Iterable interface as the aggregate interface is an extension of the Iterable interface.

It has just one abstract method. in other words,

Iterator<T> iterator ()

Iterator interface

The Iterator UI provides the ability to iterate elements forward only.

Iterator UI Methods The Iterator UI has only three methods. They are: 


Array list

We can access dynamic arrays using Java thanks to the ArrayList class. It may operate more slowly than traditional arrays, but in high-traffic scenarios, it can be helpful. An ArrayList's count automatically increases as new members are added, and it automatically decreases when elements are removed. Java ArrayList allows for random access to the list. Older data types that are incompatible with ArrayList include char, int, and so on. In these cases, you need a wrapper class.

Let's understand ArrayList with the below example.

// Below Java program to show how the ArrayList works

Linked list

One technique to build the linear LinkedList data structure is with the LinkedList class. It handles each element as an individual object with data and an address component, and stores items in non-contiguous places. The parts are linked via pointers and addresses. A node is an individual component.

Let's use the following example to better understand Linked Lists.

let us try with an example:

// Below program to show the working of LinkedList in Java

Vector

In Java, we may access dynamic arrays via a vector. It may work slower than regular arrays, but it may be useful for systems that need to manipulate arrays extensively. The implementation of this is the same as that of ArrayList. But the main distinction between an array list and a vector is that the former is non-synchronized while the latter is.

Let's use an example to better grasp the Vector.

// Below program to shows the working of Vector in Java

// working of Vector

Stack

The stack data structure is implemented and modeled by the Stack class. The last-in, first-out policy governs the class. This class additionally has the empty, search, and peek methods in addition to the regular push and pop methods. Another name for the class is the Vector subclass.

Let's use an example to better grasp the stack.

// Below program to shows the working of a stack in Java

// working of a stack

Queue interface

The queue interface follows the First In First Out (FIFO) protocol, much like a real queue would. This interface can handle all of the components if the order is important. Every time we try to book a ticket, we witness this in action because there are relatively few available. As a result, the ticket will be given to the person whose request is next in line. There are several classes available, including Array-Deque and Priority-Queue. Since all of these subclasses implement Queue, if we want or need then we can use any of them to construct a Queue object.

  1. Queue<String> q1 = new PriorityQueue();  
  2. Queue<String> q2 = new ArrayDeque();

 

Priority queue

When processing items depending on their priority, a priority queue is used. The Priority-Queue class is used when processing the queue's items based on priority is necessary, even if it is widely known that the queue runs on a First-In, First-Out basis. Priority-Queue is fundamentally a priority queue. The priority queue items are sorted using either the Comparator that is specified when the queue is established or by natural order, depending on which constructor was used.

By understating the below code we can also understand the priority queue:

// priority queue in Java

Deque interface

In this instance, the Queue data structure has undergone some modification. Double queues are another type of data structure that is similar to a queue, let us add and delete bits from both ends. Compared to the queue interface, this interface is superior. The Array-Deque class makes use of this interface. We may create a deque object by implementing the Deque interface with the help of the Array-Deque class.

Deque d = new ArrayDeque();

Array deque

Array-Deque is a class that complies with the Deque specification. Deque's use is made easier by this. In contrast to a queue, we can add and remove things from both ends.

There is no size restriction for Array-Deque, and it is quicker than ArrayList and Stack.

Let’s look at the below code example.

Set interface

An array is a non-recursive set of items that prevents duplicate data from being stored. We use this collection when we wish to preserve only unique things in our collection and not any that overlap. This set interface is used by numerous classes, such as LinkedHashSet, TreeSet, HashSet, and many more. Since all of these classes implement a set, you may use any of them to create a set object.

For example.

Set<data-type> s1 = new HashSet<data-type>();  

Set<data-type> s2 = new LinkedHashSet<data-type>();  

Set<data-type> s3 = new TreeSet<data-type>();

Classes that implement the set interface

Harsh-set

The HashSet class, a private variant of the hash-table data structure, is utilized inside. It cannot be guaranteed that elements that are addable to a hash set will be added in a predetermined sequence. Every item is placed based on its hash code. Additionally, NULL objects are allowed in this class. To help you understand HashSet, consider this example.

// working of a HashSet


Sorted set interface

This interface and the fixed interface have several things in common. The only way this interface is different is that it offers additional techniques for maintaining element order. The Sorted-Set interface extends the Set interface to provide a more convenient way to handle sorted data. Without the TreeSet class, you cannot construct this interface. Since this class is an implementation of Sorted-Set, Sorted-Set instances can be created using it.

SortedSet<data-type> set = new TreeSet();

Tree set

What the TreeSet class uses is a storage tree. The array will use the elements' natural order to maintain order whether or not an explicit comparator is provided. If the set interface is incompatible with its peers, it cannot be implemented correctly. It can also be purchased with a Comparator that is meant to be delivered at a certain construction time, depending on the builder. An example will help you better understand TreeSet.

Map interface

A map is one tool for organizing data that lets you work with key-value pairs. This interface does not support duplicate keys since a single key cannot have multiple mappings. Nevertheless, duplicate values can exist for separate keys. The map comes in helpful when the data is already available and we want to use the key to conduct actions. Many classes implement this Map interface, such as HashMap, Tree-Map, and others. All of these classes implement Map, thus we can use any of them to generate a Map object.

Map<T> hm = new HashMap<> (); 

Map<T> tm = new TreeMap<> ();

 

Where T is the type of the object

Hash map

HashMap offers a basic Java implementation of the map interface. Data is stored using pair notation (key, value). To retrieve the value of a hash map, we must know its key. HashMap employs the hashing method. Hashing may be used to break up large strings into smaller ones that nonetheless represent the same string for more effective indexing and search operations. HashMap is also used internally by HashSet. Let's examine HashMap as an illustration.

JAVA OOPS

 JAVA OOPS


  • ADVANTAGES AND DISADVANTAGES 
  • BEST PRACTICES IN JAVA OOPS CONCEPT 
  • CONCEPTS IN OOPS
  • WHY JAVA IS NOT PURELY OBJECT ORIENTED PROGRAMMING

Programming languages that largely rely on objects to carry out the logic provided in their source code are referred to as object-oriented programming languages, or OOPs. From the perspective of the user or observer, objects perform the roles assigned to them. Object-oriented programming eyes to use real-world programming constructs such as inheritance, hiding, polymorphism, etc. To guarantee a close relationship between data and the functions that handle it, object-oriented programming (OOP) was developed. This data is accessible to other parts of the code in addition to the problematic function.

Compared to procedural programming, object-oriented programming has the following advantages:

OOP is slower and more difficult to execute than OOP.

Innovative thinking provides programs with a strong foundation.

Object-oriented programming (OOP) promotes the "Don't repeat yourself" idea, which makes it easier to maintain, edit, and debug Java code.

Object-oriented programming (OOP) facilitates the completion of the building of reusable applications by minimizing code and development time.

Suggestion: Follow the "Don't Repeat Yourself" guideline to lessen the quantity of repetitive code. Instead of repeating the application-wide code, it would be more effective to gather it into one place and then utilize it again.

Advantages and disadvantages of oops in Java

Advantages:

If object-oriented programming in Java is new to you, you should learn about all of its advantages:

Reusability

Reusable code is defined as code that is written just once but is used again. As long as it is classified, a particular piece of code can be used as much as necessary.

Data Redundancy

One of the key advantages of Java OOP concepts is data redundancy. The same data may be produced in a data warehouse by storing it in two different places. By building on preexisting class definitions, you may use similar functions in other classes and create common class definitions.

Code Maintenance

The concept behind Java OOPs is to make it easier to maintain current code by allowing new objects to be formed with just little modifications from old ones. It enables users to continuously update and change outdated applications.

Security

Java OOP concepts like data hiding and abstraction provide limited discovery filtering. As a consequence, OOP functions only display the data that is necessary for security.

Benefits of Design

Java OOPs provide designers more creative flexibility. This leads to better models. The program eventually reaches its critical limits. It's now easy to program each non-operation separately.

Easy Debugging

The Java OOPs concept enables the use of self-contained encapsulation objects. Thus, engineers can promptly fix problems that keep coming up. Furthermore, the OOP features prevent the creation of duplicate code.

Disadvantage:

Performance

Because Java needs to be interpreted at runtime, it is slower than languages like C and C++. All operating systems are compatible with it, though. Conversely, C++ applications execute more quickly since they are built directly into binary format for every operating system.

Memory consumption

Java programs need more memory when they are running in a Java virtual machine.

Price

Java is a somewhat expensive programming language because it needs more processing power and also has high memory requirements. More reliable hardware is needed for the Java program to run.

Less machine interaction

Java is not a good fit for applications that need to run quickly and interact directly with the hardware because of its difficulty in doing so and its lack of explicit references.

Garbage Collection

Java features automatic trash collection, over which the developer has no control. It is devoid of memory-freeing functions like delete() and free().

Best Practices in Java OOP Concepts

The Java OOP paradigm aims to save time without compromising security or usability. You can get there by adhering to these object-oriented programming guidelines:

The Java philosophy of "Don't Repeat Yourself," or SEKA, is fundamental. Therefore, it's not a good idea to utilize the same code again. Try not to use more than one strategy in any one of your apps.

The first step in making your Java code future-proof is to encapsulate it by designating all methods and variables as private. As appropriate, access to "protected" can be progressively expanded. But do keep it a secret.

One of the best practices for Java object-oriented programming is to use single responsibility. In particular, you must confirm that the class has just one function. Consequently, the class may be extended for use in various settings or used independently. This helps to detangle several processes.

The open-closed design pattern is one of the best ways to implement the Java OOP concept. The classes and methods must remain open to add extensions, but they must be closed to edit. We can be confident that the tried-and-true Java OOP implementation will remain unchanged in this way. But they might also be modified to do different functions.

Let's go over the prerequisites, which involve declaring methods and passing messages before we get started. It has six parts, which start with the description of the method:

Access Modifier: describes the context in which the method can be called, or the access type of the method. There are 4 main types of access definitions in Java: This is public information that is accessible to all classes in your application.

"Protected" denotes that its access is restricted to the package that contains its definition and any subclasses that are listed inside. You can only access this property within the class that specifies it.

Proven in the identical class and package as its definition: default (defined/declared in an unmodified manner).

The method's value, or void if the function returns null, is to the left of the return type.

Procedure identifier: The guidelines for field names are the same as those for method names, notwithstanding the modest differences in procedure.

In a parameter list, which is divided by commas, input parameters are defined in parenthesis before their data type. If there are no arguments given, use empty parentheses. List of exclusions: Exceptions are expected by this function. You can define these exclusions.

You must run the code block included in parentheses, or the method body, to accomplish the intended result.

Message passing: The sending and receiving of messages allows objects to share data. Since the message is an instruction to do an action, calling an action on the receiving object produces the expected results. Objects’ names, functions’ names, and the definition of the information are all contained in a message.

After discussing the fundamentals, let's examine the four pillars of object-oriented programming (OOP). That being said, let's start by being acquainted with the features of an OO language.

The concepts of OOPS are:

1)      Class

2)      Object

3)      Method and method passing

4)      Abstraction

5)      Encapsulation

6)      Inheritance

7)      Polymorphism

 

Class

A class is a collection of objects. That is a logical entity.

It may also be viewed as a template that can be utilized to create a single object. There isn't a specific location needed for the class.

In class declarations, the following components are typically present in the following order:

* Adjectives Further details on establishing default permissions or making the class public may be found here.

Modifiers: As per custom, the class name needs to start with a capital letter and be appropriately capitalized. Potential superclass: A keyword is extended if the class name includes both the keyword and its superclass. A class cannot have more than one superclass as a descendant.

A list of all interfaces that the class implements, separated by commas and preceded by the word implements, should be included in the elements section. A single class can implement many user interfaces.

The class body, {}, is enclosed in braces {}.

Object

Any entities that can be described by their states and actions are considered objects. Items such as a table, chair, laptop, bike, pen, etc. It might be physical or logical.

Objects can be defined using class instances. An item has two properties: an address and a memory location. For objects to communicate, it is not required for them to know one other's data or code. All that has to be done is provide the message type and the response object type.

A dog is an excellent illustration of an item with characteristics like the dog’s color and its breed as well as actions like waving its hand. the tail, squealing, eating, and so on.

To begin testing out the class and object methods, let's build an application in Java:


Now we will discuss the most important pillars of the OOPS concept

1 Abstraction

The user only sees the information pertinent to their requirements when using data abstraction. Units that are unnecessary or inconsequential are not shown to the user. For example, a vehicle is defined as a car, not as a group of pieces.

Data abstraction may also be thought of as a means of separating away any unnecessary information from an object's required attributes. A thing's characteristics and behaviors, which also distinguish it from other things of its sort, can be used to classify and organize it.

See a real-world example of how to operate a car. The driver just understands that applying the brakes and pressing the gas pedal are controls; he has no understanding of what makes the automobile go faster or slower. He's not familiar with the location of the accelerator, brakes, or other controls on the automobile, nor with its internal workings. It isn't specific enough.

Java allows abstraction to be achieved through the use of abstract classes and user interfaces. We can use interfaces to achieve complete abstraction.

An abstract method lacks an implementation and only contains the specification of the method.

Introduction to an abstract class.

Encapsulation

The definition is putting information together into a single unit. It serves as a connection between the data and the code it processes. Another way to imagine encapsulation is as a barrier that keeps programs from accessing data that isn't inside its borders of protection.

Technically speaking, encapsulation means that only the member functions of a class have access to its variables and data; other classes cannot view them. Similar to data concealing, encapsulation prevents other classes from accessing the data of one class. In this sense, "encapsulation" and "data hiding" are synonymous.

Encapsulation may be implemented by a class by declaring public methods to access and set the values of all of its private variables.

Introduction Encapsulation.


Inheritance

Inheritance is one of the fundamental features of object-oriented programming, or OOP. The Java programming language has an attribute called inheritance that allows one class to utilize the fields and functions of another. The inheritance process is carried out via the extends keyword. Inheritance is one term for a "is-a" relationship.

Here are some terms that we should review that are frequently used:

A class that has its properties passed down across generations of classes is also called a superclass, root class, or inheritable class.

Classes that inherit from another type are among the many various sorts of classes that might be referred to as "subclasses." In addition to adding some of its own, a subclass can inherit the attributes and methods of its parent class.

Inheritance supports the concept of "reusability" by enabling us to create new classes when there are already existing ones, from which we may derive our own class, which already has part of the functionality we want. By doing this, we may once more utilize the fields and functionalities of an existing class.

Introduction to inheritance.

Polymorphism

Variations in an organism's ability to perform a certain function are referred to as polymorphism in biology. Create a shape (rectangle, square, etc.) or convince the client to reconsider.

Polymorphism can be achieved in Java using method overloading and overriding.

Speaking is another thing that springs to mind. A dog could bark and a cat might meow, for example.

Let us understand polymorphism in a Java program 


 

Few more concepts related to oops 
Coupling
"Relation" refers to a distinct class or dependence on information or knowledge. When classes are 
mutually aware, this happens. When one class knows another class, there is a strong relationship 
between them. The modifiers private, protected, and public can be used in Java to specify the 
visibility of a class, method, and field. Interfaces can be utilized for looser coupling as they don't have 
a setup.
Cohesion
Cohesion is defined as the ability of a component to perform a single, designated function with 
effectiveness. There is a pretty consistent way to complete a single task. We use the weakly connected
 technique to divide the task into smaller, more manageable portions. The input/output classes, 
interface, and other elements of the java.io package make it incredibly well-structured. In contrast, 
the java. util package only has a weak connection because it contains different and unrelated classes 
and interfaces.
Association
A relationship shows the relationship that exists between two or more elements. In this 
scenario, one item can be linked to an arbitrary number of other objects. There are four 
types of associations that objects can have:
One-to-one
One-to-many
Many-to-one and
Many-to-many
Here are some actual cases that assist us in understanding the connection. A nation with one prime
minister and several ministries answering to him or her is an example of a one-to-many relationship.
Additionally, a prime minister can have many ministries, many ministers, and many members of
parliament with one prime minister (many-to-one). You can establish a two-way or one-way connection.
Merging
The whole point of merging is to combine. Aggregation represents the connection in which one item 
incorporates other objects into its state. The relationships between the items it shows are only 
shaky at best. In Java, this is also known as the has connection. Take inheritance as an example to 
demonstrate the is-relationship. This is an additional technique for material reuse.
Composition
Arranging is another type of combination. A composition is an entity that, in its condition, consists of other 
things. The contained object and the dependent item are closely connected. This is the circumstance in which 
the things mentioned therein do not exist on their own. All of a parent object's offspring will be deleted along 
with it.
 

Why java is not purely object-oriented programming?

A programming language is referred to as pure or complete object-oriented if it supports or has functions that treat each component of a program as an object. Basic data types like int, char, float, bool, etc. are incompatible with it.

They are:

Data Encapsulation/Hiding-Inheritance

Polymorphism

Abstraction

All predefined types are objects

All user-defined types are objects

All operations on objects must be performed only by methods visible on objects.

Example: Smalltalk \ n

Java does not support functions 5 or 7, however, it does support functions 1, 2, 3, 4, and 6. Due to these characteristics, Java is more than just an object-oriented language:

Simple data types as objects include char, bool, float, int, and long. Smalltalk is an object-oriented language that is "pure" compared to Java and C++ since it does not differentiate between object values and primitive type values. Even the most fundamental data types in Smalltalk—characters, Booleans, and integers—are objects. Java has a collection of predefined kinds known as basic types in addition to objects.

Int a= 5;

System.out.print(A);

Static keyword: When a class is marked as static, using a Java object is not required. A static function or variable's object-oriented attribute cannot be overridden by invoking it with a dot (.) or a class object. Class of application: A wrapper class makes it feasible to convert an object from a primitive and vice versa. primitive Java lets you use int, float, etc. instead of using integer and float. To interact with an object, you don't always need to call its methods. while utilizing mathematical operations, for example.

String s1 = “ABC” + “A”;

Even with Wrapper classes, Java is not a true OOP language since it depends on built-in capabilities like Unboxing and Autoboxing. When you construct an integer rather than an int and then do math operations on it, Java will revert to utilizing the old-fashioned int type.

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular