1682529120
Neste tutorial de Java, aprendemos sobre como implementar genéricos em Java. Na linguagem de programação Java, os genéricos são introduzidos no J2SE 5 para lidar com objetos de tipo seguro.
Na programação Java, os genéricos de linguagem são introduzidos no J2SE 5 para lidar com objetos de tipo seguro. Ele detecta bugs no tempo de compilação pelo qual o código se torna estável. Qualquer tipo de objeto pode ser armazenado na coleção antes da introdução genérica. Agora, após a introdução genérica na linguagem de programação Java , os programadores são forçados a armazenar tipos de objetos específicos.
Três vantagens principais de usar genéricos são dadas abaixo:
Os genéricos permitem armazenar apenas um único tipo de objeto. Portanto, diferentes tipos de objetos não podem ser armazenados em genéricos.
Qualquer tipo de objeto pode ser armazenado sem genéricos.
// declaring a list with the name dataList
List dataList= new ArrayList();
// adding integer into the dataList
dataList.add(10);
// adding string data into the dataList
dataList.add("10");
Com os genéricos, precisamos informar o tipo de objeto que queremos armazenar.
Declarando uma lista com o nome dataList
List<Integer> dataList= new ArrayList();
Adicionando inteiro ao dataList
dataList.add(10);
Adicionando dados de string ao dataList
dataList.add("10"); // but this statement gives compile-time error
A conversão de tipo de objeto não é necessária com genéricos.
É necessário fazer casting antes de uma introdução genérica.
declaring a list with the name dataList
List dataList= new ArrayList();
adding an element to the dataList
dataList.add("hello");
typecasting
String s = (String) dataList.get(0);
Não há necessidade de conversão de tipo de objeto após genéricos.
// declaring a list with the name dataList
List<String> dataList= new ArrayList<String>();
// adding an element to the dataList
dataList.add("hello");
//typecasting is not required
String s = dataList.get(0);
Não ocorrerão problemas no tempo de execução, pois isso é verificado no tempo de compilação . E de acordo com boas estratégias de programação, o tratamento de problemas feito em tempo de compilação é muito melhor do que o tratamento feito em tempo de execução.
// declaring a list with the name dataList
List<String> dataList = new ArrayList<String>();
// adding an element into the dataList
dataList .add("hello");
// try to add an integer in the dataList but this statement will give compile-time error
dataList .add(32);
Sintaxe:
Generic collection can be used as :
ClassOrInterface<Type>
Example:
An example of how generics are used in java is given below:
ArrayList<String>
A classe ArrayList é usada neste exemplo. Mas no lugar da classe ArrayList, qualquer classe de framework de coleção pode ser usada, como Comparator, HashMap , TreeSet , HashSet, LinkedList, ArrayList, etc.
// importing packages
import java.util.*;
// creating a class with the name GenericsExample
class GenericsExample {
// main method
public static void main(String args[]) {
// declaring a list with the name dataList to store String elements
ArrayList < String > dataList = new ArrayList < String > ();
// adding an element into the dataList
dataList.add("hina");
// adding an element into the dataList
dataList.add("rina");
// if we try to add an integer into the dataList then it will give a compile-time error
//dataList.add(32); //compile time error
// accessing element from dataList
String s = dataList.get(1); //no need of type casting
// printing an element of the list
System.out.println("element is: " + s);
// for iterating over the dataList elements
Iterator < String > itr = dataList.iterator();
// iterating and printing the elements of the list
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Saída
element is: rina
hina
rina
Neste, estamos usando um mapa para demonstrar o exemplo genérico. O mapa permite o armazenamento de dados na forma de pares chave-valor.
// importing packages
import java.util.*;
// creating a class with the name GenericsExample
class GenericsExample {
// main method
public static void main(String args[]) {
// declaring a map for storing keys of Integer type with String values
Map < Integer, String > dataMap = new HashMap < Integer, String > ();
// adding some key value into the dataMap
dataMap.put(3, "seema");
dataMap.put(1, "hina");
dataMap.put(4, "rina");
// using dataMap.entrySet()
Set < Map.Entry < Integer, String >> set = dataMap.entrySet();
// creating an iterator for iterating over the dataMap
Iterator < Map.Entry < Integer, String >> itr = set.iterator();
// iterating for printing every key-value pair of map
while (itr.hasNext()) {
// type casting is not required
Map.Entry e = itr.next();
System.out.println(e.getKey() + " " + e.getValue());
}
}
}
Saída:
1 hina
3 seema
4 rina
Uma classe genérica é uma classe que pode se referir a qualquer tipo. E aqui, para criar um determinado tipo de classe genérica, estamos usando o parâmetro do tipo T.
A declaração de uma classe genérica é muito semelhante à declaração de uma classe não genérica, exceto que a seção do parâmetro de tipo é escrita após o nome da classe. Parâmetros de um ou mais de um tipo são permitidos na seção de parâmetro de tipo.
Uma declaração de classe genérica se parece com uma declaração de classe não genérica, exceto que o nome da classe é seguido por uma seção de parâmetro de tipo. Como um ou mais parâmetros são aceitos, tipos parametrizados ou classes parametrizadas são alguns outros nomes para isso.
E o exemplo é dado abaixo para demonstrar o uso e criação de classes genéricas.
class GenericClassExample < T > {
T object;
void addElement(T object) {
this.object = object;
}
T get() {
return object;
}
}
Aqui o tipo T representa que pode se referir a qualquer tipo, como Employee, String e Integer. O tipo especificado por você para a classe é usado para armazenamento e recuperação de dados.
Let us see an example for a better understanding of generic class usage
// creating a class with the name GenericExample
class GenericExample {
// main method
public static void main(String args[]) {
// using the generic class created in the above example with the Integer type
GenericClassExample < Integer > m = new GenericClassExample < Integer > ();
// calling addElement for the m
m.addElement(6);
// if we try to call addElement with the string type element then it will give a compile-time error
//m.addElement("hina"); //Compile time error
System.out.println(m.get());
}
}
Saída
6
Semelhante à classe genérica, também podem ser criados métodos genéricos. E qualquer tipo de argumento pode ser aceito pelo método genérico. A declaração do método genérico é apenas semelhante à do tipo genérico, mas o escopo do parâmetro de tipo é limitado ao método onde sua declaração foi feita. Os métodos genéricos podem ser estáticos e não estáticos.
Vamos entender o método genérico de Java com um exemplo. Aqui está um exemplo de impressão dos elementos de um array . Aqui E é usado para representar elementos.
// creating a class with the name GenericExample
public class GenericExample {
// creating a generic method for printing the elements of an array
public static < E > void printElements(E[] elements) {
// iterating over elements for printing elements of an array
for (E curElement: elements) {
System.out.println(curElement);
}
System.out.println();
}
// main method
public static void main(String args[]) {
// declaring an array having Integer type elements
Integer[] arrayOfIntegerElements = {
10,
20,
30,
40,
50
};
// declaring an array having character-type elements
Character[] arrayOfCharacterElements = {
'J',
'A',
'V',
'A',
'T',
'P',
'O',
'I',
'N',
'T'
};
System.out.println("Printing an elements of an Integer Array");
// calling generic method printElements for integer array
printElements(arrayOfIntegerElements);
System.out.println("Printing an elements of an Character Array");
// calling generic method printElements for character array
printElements(arrayOfCharacterElements);
}
}
Saída:
Printing an elements of an Integer Array
10
20
30
40
50
Printing an elements of an Character Array
J
A
V
A
T
P
O
I
N
T
Elementos curinga em genéricos são representados pelo símbolo de ponto de interrogação (?). E qualquer tipo é representado por ele. Se <? extends Number> é escrito por nós, isso significa qualquer número como classe filha (double, float e Integer). Agora o método de classe number pode ser chamado de qualquer uma das classes filhas. Os curingas podem ser usados como um tipo de variável local, tipo de retorno, campo ou parâmetro. Mas os curingas não podem ser usados como argumentos de tipo para a invocação do método genérico ou para a criação de uma instância de genérico.
Vamos entender os curingas nos genéricos do Java com a ajuda do exemplo abaixo dado:
// importing packages
import java.util.*;
// creating an abstract class with the name Animal
abstract class Animal {
// creating an abstract method with the name eat
abstract void eat();
}
// creating a class with the name Cat which inherits the Animal class
class Cat extends Animal {
void eat() {
System.out.println("Cat can eat");
}
}
// creating a class with the name Dog which inherits the Animal class
class Dog extends Animal {
void eat() {
System.out.println("Dog can eat");
}
}
// creating a class for testing the wildcards of java generics
class GenericsExample {
//creating a method by which only Animal child classes are accepted
public static void animalEat(List << ? extends Animal > lists) {
for (Animal a: lists) {
//Animal class method calling by the instance of the child class
a.eat();
}
}
// main method
public static void main(String args[]) {
// creating a list of type Cat
List < Cat > list = new ArrayList < Cat > ();
list.add(new Cat());
list.add(new Cat());
list.add(new Cat());
// creating a list of type Dog
List < Dog > list1 = new ArrayList < Dog > ();
list1.add(new Dog());
list1.add(new Dog());
// calling animalEat for list
animalEat(list);
// calling animalEat for list1
animalEat(list1);
}
}
Saída:
Cat can eat
Cat can eat
Cat can eat
Dog can eat
Dog can eat
O principal objetivo do uso de curingas de limite superior é reduzir as restrições variáveis. Um tipo desconhecido é restrito por ele para ser um tipo particular ou subtipo de um tipo particular. Os curingas de limite superior são usados escrevendo um símbolo de ponto de interrogação e, em seguida, estendendo a palavra-chave se houver uma classe e implementando uma palavra-chave para a interface e, em seguida, o limite superior é escrito.
Sintaxe do curinga de limite superior
? extends Type.
Exemplo de curinga de limite superior
Vamos entender o curinga de limite superior com um exemplo. Aqui, os curingas de limite superior são usados por nós para a escrita do método List<Double> e List<Integer>.
// importing packages
import java.util.ArrayList;
// creating a class with the name UpperBoundWildcardExample
public class UpperBoundWildcardExample {
// creating a method by using upper bounded wildcards
private static Double sum(ArrayList << ? extends Number > list) {
double add = 0.0;
for (Number n: list) {
add = add + n.doubleValue();
}
return add;
}
// main method
public static void main(String[] args) {
// creating a list of integer type
ArrayList < Integer > list1 = new ArrayList < Integer > ();
// adding elements to the list1
list1.add(30);
list1.add(40);
// calling sum method for printing sum
System.out.println("Sum is= " + sum(list1));
// creating a list of double type
ArrayList < Double > list2 = new ArrayList < Double > ();
list2.add(10.0);
list2.add(20.0);
// calling sum method for printing sum
System.out.println("Sum is= " + sum(list2));
}
}
Saída:
Sum is= 70.0
Sum is= 30.0
A lista de tipo desconhecido é especificada pelos curingas ilimitados como List<?>.
Exemplo de Curingas Ilimitados
// importing packages
import java.util.Arrays;
import java.util.List;
// creating a class with the name UnboundedWildcardExample
public class UnboundedWildcardExample {
// creating a method displayElements by using Unbounded Wildcard
public static void displayElements(List << ? > list) {
for (Object n: list) {
System.out.println(n);
}
}
// main method
public static void main(String[] args) {
// creating a list of type integer
List < Integer > list1 = Arrays.asList(6, 7, 8);
System.out.println("printing the values of integer list");
// calling displayElements for list1
displayElements(list1);
// creating a list of type string
List < String > list2 = Arrays.asList("six", "seven", "eight");
System.out.println("printing the values of string list");
// calling displayElements for list2
displayElements(list2);
}
}
Saída:
printing the values of integer list
6
7
8
printing the values of string list
six
seven
eight
Os curingas de limite inferior são usados para restringir o tipo desconhecido a ser um tipo específico ou o supertipo do tipo específico. Os curingas de limite inferior são usados escrevendo um símbolo de ponto de interrogação seguido pela palavra-chave super e, em seguida, escrevendo o limite inferior.
Sintaxe do curinga de limite inferior
? super Type.
Exemplo de curinga de limite inferior
// importing packages
import java.util.*;
// creating a class with the name LowerBoundWildcardExample
public class LowerBoundWildcardExample {
// creating a method by using upper bounded wildcards
private static void displayElements(List << ? super Integer > list) {
for (Object n: list) {
System.out.println(n);
}
}
// main method
public static void main(String[] args) {
// creating a list of type integer
List < Integer > list1 = Arrays.asList(6, 7, 8);
System.out.println("printing the values of integer list");
// calling displayElements for list1
displayElements(list1);
// creating a list of type string
List < Number > list2 = Arrays.asList(8.0, 9.8, 7.6);
System.out.println("printing the values of string list");
// calling displayElements for list2
displayElements(list2);
}
}
Saída:
printing the values of integer list
6
7
8
printing the values of string list
8.0
9.8
7.6
Fonte do artigo original em: https://dzone.com
1600135200
OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.
In this article, we will be installing OpenJDK on Centos 8.
#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment
1620458875
According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.
What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.
In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var
. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var
has on other pre-existing characteristics.
#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity
1620462686
On March 16th, 2021, Java 16 was GA. With this new release, tons of new exciting features have been added. Check out the release notes to know more about these changes in detail. This article’s focus will be on Java Records, which got delivered with JEP 395. Records were first introduced in JDK 14 as a preview feature proposed by JEP 359, and with JDK 15, they remained in preview with JEP 384. However, with JDK 16, Records are no longer in preview.
I have picked Records because they are definitely the most favored feature added in Java 16, according to this Twitter poll by Java Champion Mala Gupta.
I also conducted a similar survey, but it was focused on features from Java 8 onwards. The results were not unexpected, as Java 8 is still widely used. Very unfortunate, though, as tons of new features and improvements are added to newer Java versions. But in terms of features, Java 8 was definitely a game-changer from a developer perspective.
So let’s discuss what the fuss is about Java Records.
#java #springboot #java programming #records #java tutorials #java programmer #java records #java 16
1602637135
Java is not the hardest language to start with. So, it becomes way popular among novice developers joining the ranks of Java coders every single day. If you are reading this blog post, you might be interested in learning Java.
Java is widely used across industry, and especially in the area of Enterprise software, which results in many high paying job opportunities and makes this programming language a common language for newbies. A general promotion of it within colleges and other institutions providing a formal Computer Science education also contributes to its popularity.
However, these are not the only advantages of Java — among other things, it allows you to adopt good practices and makes it way easier to learn other languages in the future. And with no doubt, you can easily learn it if you’re following the right approach. In this post, I am going to share some of them with you.
Beyond all doubt, practice is important and valuable. But, before we get to the advantages of hands-on experience, I want to draw your attention to one essential thing I often tell my students.
New programmers who are just learning and start implementing things, without being supervised, often end up adapting bad practices. To avoid that, especially when you are making your first steps in programming, I recommend looking for a person who will supervise you and teach you. A strong mentorship with someone engaged in a serious project, as well as communication within the community in the form of sharing code and asking for feedback, is worth the effort. Similarly, when you are applying for your first job, you want to be looking for a company with a strong team and a good leader who would be keen on investing into your learning.
Now, let’s return to practical experience. Learning by doing is different from learning by passively consuming the information. To make sure we can use all the newly acquired technology, we should put our skills to test and write tons of code. The benefits of hands-on experience are almost endless.
By practicing, you get a clear understanding of what programming is. Consequently, you start doing better with each new hands-on task, complete it faster, and thus become more productive.
Even if you are not working on real-world projects yet, it’s important to get used to having deadlines. They are inextricably linked to the programming process. My recommendation is to set up your own deadlines while practicing stage and follow them as closely as possible.
#java #learn java #java code #learn java in easy way #learn java course #learn java development
1624948542
In this blog we will understand what is the lambda expression and why we need lambda expression and how we use lambda and about the functional interface.
#functional programming #java #functional java #java #java 8 #java8 #lambda expressions in java