10 Java Tips – Series II

Java Tips

Java Tips – Series II

Įvadas : This is the 2nd part of Java tips series. We have tried to focus more on the hands-on coding part rather that the theoretical one. Tikimės, kad tai padės jums išmokti sąvokas ir įgyvendinti juos praktiniuose projektuose,,en,Tai taip pat padės jums pasirengti "Java" apklausoms,,en,Mėgaukitės skaitymu,,en,Kas yra kolekcijos sistema Java,,en,Kolekcija yra objektų grupė,,en,"java.util" paketas suteikia svarbių kolekcijų tipų,,en,Yra dvi pagrindinės kolekcijų rūšys: kolekcija ir žemėlapis,,en,Kolekcijos tipai turi objektų grupę,,en,kaip sąrašai ir rinkiniai,,en,Tačiau žemėlapių tipai laiko objektų grupę raktu,,en,vertės poros, tokios kaip "HashMap" ir "Hashtable",,en,Kolekcijų sistema,,en,yra viena iš svarbiausių "Java" platformos sričių,,en,Kaip išplėsti masyvą po iniciacijos,,en,Toliau pateiktas pavyzdys parodo, kaip išplėsti masyvą po iniciacijos, sukurdami naują masyvą,,en,Čia kodas iš esmės prideda naujas esamos masyvo reikšmes,,en,Arraikoopija,,en. It will also help you to prepare for Java based interviews. Enjoy reading.







What is collections framework in java?

A: Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, like Lists and Sets. But Map types hold group of objects as key, value pairs like HashMap and Hashtable. Collections framework is one of the most important area in Java platform.

How to extend an array after initialization?

A: Following example shows how to extend an array after initialization by creating a new array. Here the code is basically appending the new values to an existing array. The arraycopy() metodas turėtų būti naudojamas atidžiai, kitaip gali kilti duomenų praradimo esama masyvo problema,,en,names = nauja eilutė,,en,X,,en,pratęstas = naujas eilutė,,en,pratęstas,,en,System.arraycopy,,en,names.length,,en,String str,,en,Ir rezultatas bus toks,,en,Kaip užpildyti,,en,inicijuoti vienu metu,,en,masyvas,,en,Šis pavyzdys užpildys,,en,inicijuokite visus elementus masyvo vienu trumpu,,en,masyvas naudojant Array.fill,,en,Arrayname,,en,metodas ir Array.fill,,en,pradžios indeksas,,en,pabaigos indeksas,,en,Java klasės "Util" metodas,,en,viešoji klasė FillTest,,en,int masyvas,,en,= naujas int,,en,Arrays.fill,,en,n = masyvo ilgis,,en,Jei paleisite kodą, rezultatas bus toks,,en,Kaip dauginti dvi skirtingų matricų matricas,,en,Toliau pateiktame pavyzdyje parodoma, kad dviejų stačiakampių matricų dauginimas, naudojant du vartotojo apibrėžtus metodus, dauginamas,,en,ir mprint,,en,viešoji klasė matrica,,en,viešoji statinė int,,en,padauginti,,en,m1,,hmn,m2,,en,int m1rows = m1.length,,en.

public class Main {

public static negaliojančiu pagrindinis(Styga[] args) {

Styga[] names = new String[] { “X”, “Y”, “Z” };

Styga[] extended = new String[5];

extended[3] = “D”;

extended[4] = “Jis”;

System.arraycopy(names, 0, extended, 0, names.length);

už (String str : extended){

System.out.println(str);

}

}

}

And the result will be as follows

X
Y
Z
D
Jis

How to fill (initialize at once) an array?

A: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, vertė) method and Array.fill (arrayname, starting index, ending index, vertė) method of Java Util class.

import java.util.*;

public class FillTest {

public static negaliojančiu pagrindinis(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

už (int i=0, n=array.length; aš < n; i ) {

System.out.println(array[aš]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

už (int i=0, n=array.length; aš< n; i ) {

System.out.println(array[aš]);

}

}

}

If you run the code then the result will be as follows.

100
100
100
100
100
100
100
100
100
50
50
50

How to multiply two matrices of different dimensions?

A: Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply ( int [] [] ,int [] []) and mprint(int [] []).

public class Matrix{

public static int[][] multiply(int[][] m1, int[][] m2){

int m1rows = m1.length;

int m1cols = m1,,en,ilgis,,en,int m2rows = m2.length,,en,int m2cols = m2,,en,m1cols,,en,= m2rows,,en,mesti naują "IllegalArgumentException",,en,matricos,,en,nesutampa,,en,m2rows,,en,rezultatas = naujas int,,en,M1rows,,en,m2cols,,en,int j = 0,,en,int k = 0,,en,= m1,,hmn,grąžinimo rezultatas,,en,Matricos spausdinimas,,en,viešas statinis tuščias spausdinimas,,en,int eilutės = a.length,,en,int cols = a,,ca,eilutės ,,en,cols ,,en,eilutės,,en,argv,,en,int x,,en,int ir,,es,int nuo,,pl,= Matrix.multiply,,en,Matrix.mprint,,en,Kodo pavyzdys duos tokį rezultatą,,en,Kaip sujungti du masyvus,,en,Šis pavyzdys rodo, kaip sujungti du masyvus į vieną masyvą naudojant list.Addall,,en,array1.asList,,en,array2,,en,metodo sąrašo klasė ir masyvai.toString,,en,Array klasės metodas,,en,Būkite atsargūs, priskirdami vieną masyvą kitam,,en,Kadangi, jei abu matricų elementų nuorodos yra, tai yra tikimybė, kad bus pakopinis efektas,,en,import java.util.Arrays,,en,Styga a,,en,Styga b,,en,O,,pt,U,,bs,Sąrašas sąrašas = naujas ArrayList,,en,Arrays.asList,,en[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

jei (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

don’t match: “+ m1cols + ” != ” + m2rows);

int[][] result = new int[m1rows][m2cols];

už (int i=0; aš< m1rows; i ){

už (int j=0; j< m2cols; j ){

už (int k=0; k< m1cols; k ){

result[aš][j] += m1[aš][k] * m2[k][j];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(int[][] a){

int rows = a.length;

int cols = a[0].length;

System.out.println(“array[“+rows ”][“+cols ”] = {“);

už (int i=0; aš< rows; i ){

System.out.print(“{“);

už (int j=0; j< cols; j ){

System.out.print(” ” + a[aš][j] + “,”);

System.out.println(“},”);

}

}

System.out.println(“:;”);

}

public static negaliojančiu pagrindinis(Styga[] argv){

int x[][] ={

{ 3, 2, 3 },

{ 5, 9, 8 },

};

int y[][] ={

{ 4, 7 },

{ 9, 3 },

{ 8, 1 },

};

int z[][] = Matrix.multiply(x, y);

Matrix.mprint(x);

Matrix.mprint(y);

Matrix.mprint(z);

}

}

The code sample will produce the following result

array[2][3]={

{3, 2, 3}

{5, 9, 8}

};

array[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

array[2][2]={

{63, 30}

{165, 70}

};







How to merge two arrays?

A: This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class. Be careful when assigning one array to another. Because if the references of the elements of both the arrays then there is chance of cascading effect.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static negaliojančiu pagrindinis(String args[]) {

String a[] = { “A”, “Jis”, “I” };

String b[] = { “O”, “U” };

List list = new ArrayList(Arrays.asList(a));

list.addAll,,en,c = list.toArray,,en,Arrays.toString,,en,Kaip ieškoti mažiausio ir didžiausio elemento masyvo,,en,Šis pavyzdys rodo, kaip ieškoti mažiausio ir didžiausio elemento masyvo, naudojant "Collection.max",,en,ir Collection.min,,en,Kolekcijos klasės metodai,,en,Nors yra keletas kitų būdų taip pat rasti masyvo max ir min reikšmes, tačiau šis API yra pats efektyviausias dirbant su masyvais,,en,import java.util.Collections,,en,numeriai =,,en,int min =,,ar,Collections.min,,en,numeriai,,en,int max =,,en,Collections.max,,en,Min. Numeris,,en,aš,,ku,Maksimalus skaičius,,en,maks,,en,Rezultatas bus toks,,en,Kaip pakeisti arrailistą,,en,Kolekcijų API yra metodas, vadinamas atgaline data,,en,ArrayList,,en,Taigi tai naudojama masyvo sąrašo keitimui,,en,Šiame pavyzdyje bus parodyti, kaip naudoti API, kad kodas veiktų,,en,ArrayList arrayList = naujas ArrayList,,en,arrayList.add,,en(Arrays.asList(b));

Object[] c = list.toArray();

System.out.println(Arrays.toString(c));

}

}

The code sample will produce the following result

[A, Jis, I, O, U]

How to search the minimum and the maximum element in an array?

A: This example shows how to search the minimum and maximum element in an array by using Collection.max () and Collection.min() methods of Collection class. Although there are some other ways also to find the max and min values from an array but this API is the most efficient one to work with arrays.

import java.util.Arrays;

import java.util.Collections;

public class Main {

public static negaliojančiu pagrindinis(Styga[] args) {

Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};

int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println(“Min number: ” + min);

System.out.println(“Max number: ” + max);

}

}

The result will be as follows

Min number: 1

Max number: 9

How to reverse an arraylist?

A: Collections API has a method called reverse (ArrayList). So this is used to reverse an array list. The following example will show you how to use the API to make the code work.

import java.util.ArrayList;

import java.util.Collections;

public class Main {

public static negaliojančiu pagrindinis(Styga[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“B”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“Jis”);

System.out.println(“Prieš atvirkštinį užsakymą,,en,arrayList,,en,Collections.reverse,,en,Po atvirkštinio užsakymo,,en,Pirmiau pateikto pavyzdžio rezultatas būtų toks:,,en,Kaip rūšiuoti masyvą ir į jį įterpti elementą,,en,Toliau pateiktas pavyzdys rodo, kaip naudoti rūšiavimą,,en,metodas ir vartotojo nustatytas metodas įterpti elementą,,en,atlikti užduotį,,en,Rūšiuoti,,en,metodas yra naudojamas masyvo rūšiavimui nuo neigiamos iki teigiamos reikšmės, tada pritaikytas įterpimo elementas,,en,metodas yra naudojamas papildomiems elementams į jį įtraukti,,en,viešoji klasė MainClass,,en,Arrays.sort,,en,printArray,,en,Rūšiuoti masyvas,,en,int index = Arrays.binarySearch,,en,Nepavyko rasti,,en,@,,en,int newIndex = -index,,en,masyvas = įterpti elementą,,en,newIndex,,en,Su,,en,privatus statinis void printArray,,en,array.length,,en,privatus statinis int,,en,įterpti elementą,,en,int originalas,,en,int elementas,,en,int indeksas,,en,int ilgis = original.length,,en,int paskirties vieta,,en,originalus,,en,= elementas,,en,grįžti paskirties vieta,,en: ” + arrayList);

Collections.reverse(arrayList);

System.out.println(“After Reverse Order: ” + arrayList);

}

}

The result of the above example would be as follows.

Prieš atvirkštinį užsakymą,,en,arrayList,,en,Collections.reverse,,en,Po atvirkštinio užsakymo,,en,Pirmiau pateikto pavyzdžio rezultatas būtų toks:,,en,Kaip rūšiuoti masyvą ir į jį įterpti elementą,,en,Toliau pateiktas pavyzdys rodo, kaip naudoti rūšiavimą,,en,metodas ir vartotojo nustatytas metodas įterpti elementą,,en,atlikti užduotį,,en,Rūšiuoti,,en,metodas yra naudojamas masyvo rūšiavimui nuo neigiamos iki teigiamos reikšmės, tada pritaikytas įterpimo elementas,,en,metodas yra naudojamas papildomiems elementams į jį įtraukti,,en,viešoji klasė MainClass,,en,Arrays.sort,,en,printArray,,en,Rūšiuoti masyvas,,en,int index = Arrays.binarySearch,,en,Nepavyko rasti,,en,@,,en,int newIndex = -index,,en,masyvas = įterpti elementą,,en,newIndex,,en,Su,,en,privatus statinis void printArray,,en,array.length,,en,privatus statinis int,,en,įterpti elementą,,en,int originalas,,en,int elementas,,en,int indeksas,,en,int ilgis = original.length,,en,int paskirties vieta,,en,originalus,,en,= elementas,,en,grįžti paskirties vieta,,en: [A, B, C, D, Jis]

After Reverse Order: [Jis, D, C, B, A]







How to sort an array and insert an element inside it?

A: The following example shows how to use sort () method and user defined method insertElement () to accomplish the task. The sort () method is used to sort the array from negative to positive value then the customized insertElement () method is used to add additional elements into it.

import java.util.Arrays;

public class MainClass {

public static negaliojančiu pagrindinis(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 1);

System.out.println(“Didn’t find 1 @ ”

+ index);

int newIndex = -index – 1;

array = insertElement(array, 1, newIndex);

printArray(“With 1 added”, array);

}

private static void printArray(Styginių pranešimą, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

už (int i = 0; aš < array.length; i ) {

jei (aš != 0){

System.out.print(“, “);

}

System.out.print(array[aš]);

}

System.out.println();

}

private static int[] insertElement(int original[],

int element, int index) {

int length = original.length;

int destination[] = new int[length + 1];

System.arraycopy(original, 0, destination, 0, index);

destination[index] = element;

System.arraycopy(original, index, destination, index

+ 1, length – index);

return destination;

}

}

Kaip rūšiuoti masyvą ir ieškoti elemento viduje,,en,ir binarySearch,,en,metodas užduočiai atlikti,,en,Vartotojo nustatytas metodas printArray,,en,naudojamas rodyti produkciją,,en,mport java.util.Arrays,,en,Jei paleisite kodą, programa parodys rezultatą, kaip nurodyta žemiau,,en,Kaip sukurti reklamjuostę naudojant "Applet",,en,Šiame pavyzdyje naudojama "Thread" klasė ir "Graphics" klasė, kad būtų rodomas reklamjuostė,,en,Siūlo funkcija - suteikti animacijos efektą į reklamjuostę,,en,Norėdami peržiūrėti išvesties, programa turi būti paleista naršyklėje, palaikančiame apletu,,en,importuoti java.applet. *,,en,viešoji klasė "SampleBanner" pratęsia "Applet",,en,įgyvendina Runnable,,en,String str =,,en,Tai paprasta reklamjuostė,,en,Temos t,,en,Būlio b,,en,viešas void init,,en,Color.gray,,en,setForeground,,en,Spalva,,en,viešas negaliojantis pradžia,,en,t = nauja gija,,en,b = klaidinga,,en,t.start,,en,viešoji void paleisti,,en,char ch,,en?

A: The following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output.

mport java.util.Arrays;

public class MainClass {

public static negaliojančiu pagrindinis(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 2);

System.out.println(“Found 2 @ ” + index);

}

private static void printArray(Styginių pranešimą, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

už (int i = 0; aš < array.length; i ) {

jei(aš != 0){

System.out.print(“, “);

}

System.out.print(array[aš]);

}

System.out.println();

}

}

If you run the code then the application will show the result as given below.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5

How to create a banner using Applet?

A: The following example has used the Thread class and Graphics class to display the banner. The functionality of the thread is to give an effect of animation to the banner. To view the output the applet should be run In a browser which supports applet.

importo java.awt. *;

import java.applet.*;

public class SampleBanner extends Applet

implements Runnable{

String str = “This is a simple Banner “;

Thread t ;

boolean b;

public void init() {

setBackground(Color.gray);

setForeground(Color.yellow);

}

public void start() {

t = new Thread(this);

b = false;

t.start();

}

public void run () {

char ch;

už( ; ; ) {

pabandyti {

perparduoti,,en,ch = str.charAt,,en,str = str.substring,,en,str.length,,en,str = p,,ro,Ch,,en,viešas void dažai,,en,Grafika g,,en,g.drawRect,,en,g.setColor,,en,g.fillRect,,en,Color.red,,en,g.drawString,,en,Jus gali sudominti,,en,Java patarimai serija I,,en();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

}

sugauti(InterruptedException e) {}

}

}

public void paint(Graphics g) {

g.drawRect(1,1,300,150);

g.setColor(Color.yellow);

g.fillRect(1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}

}








You may be interested in Java Tips Series I also. Enjoy reading.

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share