Przejdź do głównej zawartości

Posty

Caused by: java.net.BindException: Address already in use: JVM_Bind

Pierwsze starcie z Eclipse Ruszam z WebServlet App na Eclipse. Mave Build zwraca informacje ze port jest zajęty pod 8080 Caused by: java.net.BindException: Address already in use: JVM_Bind Rozwiązanie C:\>netstat -ano | find "8080" TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING        26732 TCPView - dnjajdujemy PID i ubijamy dany proces

Sorting algor

BubbleSort // BubbleSort System . out . println ( "BubbleSort" ); for ( int i = 0 ; i < data . length - 1 ; i ++){ for ( int j = 0 ; j < data . length - 1 - i ; j ++){ if ( data [ j ] > data [ j + 1 ]) { int temp = data [ j ]; data [ j ]= data [ j + 1 ]; //swap data [ j + 1 ]= temp ; } } } mało efektywny z uwagi na podwójny loop tylko do małych data sets efektywność O(n^2) SelectionSort raczej wolny algorytm z uwagi na podwójny loop małe data set efektywność O(n^2) System . out . println ( "SelectionSort" ); int i , j , minV , minI , temp = 0 ; for ( i = 0 ; i < data . length ; i ++){ minV = data [ i ]; minI = i ; for ( j = i ; j < data . length ; j ++){ if ( data [...

Stream peak() metoda - Java

API Note: This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline: Stream.of("one", "two", "three", "four") .filter(e -> e.length() > 3) .peek(e -> System.out.println("Filtered value: " + e)) .map(String::toUpperCase) .peek(e -> System.out.println("Mapped value: " + e)) .collect(Collectors.toList()); Metoda pozwala wyprintować aktualny stan streamu. Rodzaje operacji na strumieniach: posredniczace tzw intermediate kończące - tzw terminal bezstanowe - np filter stanowe - sort redukcyjne - np max WAZNE Strumienie są wywoływane w sposób leniwy (lazy) tzn dane sa przetwarzane w momencie wywołania metody końcowej tj terminal Transformacje nie modyfikuja wejściowych danych z których strumień został stworzony  https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-su...

Runnable and Call able - Java rekrutacja

Runnable - interfejs zawierający metode run() - obiekt implementujący tą metodę tworzy wątek thread public interface Runnable The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.  In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclas...

wait and notify() Methods in Java - rekrutacja

Synchronizacja wątków. Procesor może wykonywać wiele zadań jednoczenśnie - concurrent software. Java wspiera współbieżność jest potrzebna synchronizacja ponieważ różne wątki threads mogą w tym samym czasie usiłować zmodyfikować ten sam zasób jeśli nie są zarządzane poprawinie. Object.wait() - zawiesza wątek - thread suspension Object.notify() - wznów wątek - thread wake up Object.notifyAll() - wznowienie wszystkich wątków

StringBuilder vs Stringbuffer

StringBuilder naleyży używać jesli zamierzamy concat wiele stringów, StringBuilder został wprowadzony od Javy5.  StringBuffer to starsza wersja StringBuildera. StringBuffer trobi to samo jednak z punktu widzenia performance jest wolniejszy gdzyż jest thread safe Thread Safety in Java  Thread safety in java is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe.  Synchronization is the easiest and most widely used tool for thread safety in java.  Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger  Use of locks from java.util.concurrent.locks package.  Using thread safe collection classes, check this post for usage of ConcurrentHashMap for thread safety.  Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache. Język Java również posiada słow...

String Pool Java Core

Co to jest String Pool? W profesjonalnej aplikacji az do 40% pamięci zajmują obiekty typu String. Dlatego w Javie mozliwe jest stworzenie specjalnej przestrzeni w pamieci do trzymania wszystkich unikalnych obiektów String które mogą być używane wieloktornie co zaoszczedza zasobów. Strin Pool a inaczej nazywane Intern Pool to miejsce w JVM któe zbiera stringi. Obikety nie literalne trafiają do GC.

Hermetyzacja raz jeszcze - java + static

Korzyści z hermetyzacji : możliwość zmianny tylko w obrębie klasy np z getName ---> return firstName + " " + lastName zamiast pierwotnego return name ograniczamy dostępność tylko do wyznaczonych parti kodu - ustawiamy dla pola private ale nie ustawiamy gettera do tego pola łatwosć w testowaniu  łatwiejsze ponowne używanie programu Modifikator static: powoduje ze nie potrzeba tworzyć obiektu klasy aby mieć dostęp do jego metod. Java przeszukuje wszystkie modyfikatory dostępu static aby dla wszystkich metod stworzyć po jednej instancji metody Zmienne będące w statycznej metodzie muszą również być statyczne aby umozliwić uruchomienie metody / programu W statycznej metodzie nie stosujemy this. gdyż nie odwołujemy się do instancji która może zostać nie zainicjalizowana Statyczna zmienna nie może być zainicjalizowana w metodzie statycznej gdyż dochodzi do problemu w którym moemncie zainicjalizować zmienną A - w moemencie startu programu B - w momencie wywoła...

Java Collection - Kolekcje w Java

Podział kolekcji w Java-ie: Implementowane są interfejsy kolor zielony w klasach kolor fiolet Kolekcje mogą być generyczne i niegeneryczne generyczne - zdefiniowany typ jaki będą przechowywać niegeneryczne - przechowują wszystko co do nich wpadnie co w nich umieścimy ArrayList : wolniejsze w manipulacji elementy sa obok siebie wolne dodawanie elementów LinkedList : szybkie umieszczanie obiektów wolniejsze odczytywanie szukanie Linkedlist – dodawanie elementów tam gdzie jest miejsce w pamięci i jednoczesne dodawanie referencji gdzie ten element się znajduje, to jest plus w kontekście ArrayList która musi przenieść cały ArrayList jeśli braknie miejsca. LinkedList pamięta referencje do lokowanych obiektów. Obiekt w LinkedList jest jakby opakowywany tj zawiera informacje nie tylko o sobie ale również posiada referencje do poprzednika i następnika.  Obiekt w LinkedList zawiera:  Obiekt sam w sobie  Ref do następnika  Ref do poprze...

Array-1 > middleWay

Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements. middleWay([1, 2, 3], [4, 5, 6]) → [2, 5] middleWay([7, 7, 7], [3, 8, 0]) → [7, 8] middleWay([5, 2, 9], [1, 4, 5]) → [2, 4] Proste rozwiązanie - nie bierze pod uwagę iż szeregi mogą mieć różna długość public int sum2 ( int [] nums ) { if ( nums . length >= 2 ) return ( nums [ 0 ] + nums [ 1 ]); if ( nums . length == 1 ) return nums [ 0 ]; return 0 ; } Rozwiązanie umożliwiające podjęcie środkowego indeksu bez względu na różnice długości poszczególnych arrayów public int [] middleWay ( int [] a , int [] b ) { int [] newNums = new int [ 2 ]; newNums [ 0 ]= a [ 0 +( a . length - 0 )/ 2 ]; newNums [ 1 ]= b [ 0 +( b . length - 0 )/ 2 ]; return newNums ; }

String-2 > repeatFront

Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n >= 0 and n <= str.length()). repeatFront("Chocolate", 4) → "ChocChoChC" repeatFront("Chocolate", 3) → "ChoChC" repeatFront("Ice Cream", 2) → "IcI" Definiujemy zmienna newStr , loop reverse schodzimy od n do 0 i kazdy substring dodajemy do nwoego newStr public String repeatFront ( String str , int n ) { String newStr = "" ; for ( int i = n ; i >= 0 ; i --){ newStr += str . substring ( 0 , i ); } return newStr ; }

String-2 > mixString

Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result. mixString("abc", "xyz") → "axbycz" mixString("Hi", "There") → "HTihere" mixString("xxxx", "There") → "xTxhxexre" Mix String: dwa stringi o roznej dlugosci Musimy przejsc loopem przez oba i zlozyc nowy string . aby miec pewnosc ze iterujemy po wszystkich char w stringu wybieramy dluzszy. Konieczne zadeklarowanie zmiennej String str ktora bedzie przechowywala kolejne char public String mixString ( String a , String b ){ String str = "" ; int len = 0 ; if ( a . length () >= b . length ()) { len = a . length (); } else len = b . length (); for ( int i = 0 ; i < len ; i ++) { if ( i...

String-2 > xyBalance

We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced. xyBalance("aaxbby") → true xyBalance("aaxbb") → false xyBalance("yaaxbb") → false Szukam char i rownego x, nastepnie musimy spwardzic czy po tym x jest y tj generujemy string i drugi warunek ten substring zaczyna sie od i w ktorym zostal odnotowany x i jedzie do konca szukajac y - jesli true to oba true jesli false wtedy false public boolean xyBalance ( String str ) { for ( int i = 0 ; i < str . length (); i ++){ if ( str . charAt ( i )== 'x' ){ if ( str . substring ( i + 1 , str . length ()). contains ( "y" )&& str . charAt ( str . length ()- 1 )!= 'x' ){ ...

String-2 > xyzThere - java

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.  xyzThere("abcxyz") → true xyzThere("abc.xyz") → false xyzThere("xyz.abc") → true Definiujemy loop ktory sprawdza za kazdym podejsciem czy kolejne indexy i,i+1 oraz i+2 i zdefiniowane dla nich char.  Nalezy tu pamietac ze jesli sprawdamy po indeksach np i+2 to tzreba zostawic "miejsce" na koncu aby nie bylo outOfBoudnExeption tj przekroczenia rlugosci stringa. Jezeli pierwszy warunek jest spelniony tj mamy na kolejnych indexach interesujace nas char-y sprawdzamy czy na poprzedzajacych nasza trojkę indexach pojawia sie "." zaczynamy od indexu 0 - tzreba to uwzglednić w warunku tj albo index 0 == 0 lub i-1 == 0 public boolean xyzThere ( String str ) { int len = str . length () - 2 ; for ( int i = 0 ; i < len ; i...

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if
Given a string, return a string where for every char in the original, there are two chars.  doubleChar("The") → "TThhee" doubleChar("AAbb") → "AAAAbbbb" doubleChar("Hi-There") → "HHii--TThheerree" Solution: easy public String doubleChar ( String str ) { String str1 = "" ; for ( int i = 0 ; i < str . length (); i ++) { str1 = str1 + str . charAt ( i ) + str . charAt ( i ); } return str1 ; } more complicated solution with Character.toString() - https://www.javatpoint.com/java-char-to-string for ( int i = 0 ; i < str . length (); i ++){ String strChar = Character . toString ( str . charAt ( i ))+ Character . toString ( str . charAt ( i )); System . out . print ( strChar ); }
Your cell phone rings. Return true if you should answer it. Normally you answer, except in the morning you only answer if it is your mom calling. In all cases, if you are asleep, you do not answer. answerCell(false, false, false) → true answerCell(false, false, true) → false answerCell(true, false, false) → false public boolean answerCell ( boolean isMorning , boolean isMom , boolean isAsleep ) { if ( isMom && ! isAsleep ){ return true ; } if ( isMorning && ! isMom ){ return false ; } if ( isAsleep ){ return false ; } return true ; }

Logic-1 > alarmClock - if(true) - instrukcja warunkowa

Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off" larmClock(1, false) → "7:00" alarmClock(5, false) → "7:00" alarmClock(0, false) → "10:00" mamy warunek isVacation true or false ktory determinuje ktorym torem pojdziemy. Instrukcja warunkowa powinna ten warunek sprawdzic jako pierwszy. if (isVacation){ . . . } else { . . . } public String alarmClock ( int day , boolean vacation ) { if ( vacation ) { if ( day == 0 || day == 6 ) return "off" ; return "10:00" ; } else { if ( day == 0 ||...

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > middleTwo

Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string length will be at least 2. middleTwo("string") → "ri" middleTwo("code") → "od" middleTwo("Practice") → "ct" public String middleTwo ( String str ) { return str . substring (( str . length ()/ 2 - 1 ), str . length ()/ 2 + 1 ); }